What happens in this case is as follows:
- Within the scope of
for
there is the variable i
, which is initialized at 0
and incremented with +1
at each "loop" that occurs because of loop%
Also within the scope of for
is created an anonymous function that receives the parameter that was also called for
by simple chance of the destination, which could be called anything, could be for example i
- From there, the variable
(funciontion(meuParametroMuitoLouco) { ...
within the anonymous function becomes the parameter received in the function, not the variable i
of i
- On the command in parentheses
for
at the end of the anonymous function it simply executes the function that has just been created anonymously by passing the variable (i)
created in the declaration of method i
The reason you do not understand what happens is because of the choice of variable names, which makes the visual separation of the code very confusing, an alternative is to change the name of the variable received as a parameter inside the anonymous function, below:
(function(indexParaDeletar) {
var id_cliente = del[indexParaDeletar].getAttribute('value');
if (del[indexParaDeletar].addEventListener) {
del[indexParaDeletar].addEventListener("click",
function() {
confirmaExclusao(id_cliente);
}
);
} else if (del[indexParaDeletar].attachEvent) {
del[indexParaDeletar].attachEvent("onclick",
function() {
confirmaExclusao(id_cliente);
}
);
}
})(i);
Another alternative is to create a function and simply call it inside the for, so that the function is not anonymous, which has the benefit of assisting in the console / browser error log, separating responsibilities, improving code readability , etc, etc, etc, for example:
function deletar(indexParaDeletar) {
var id_cliente = del[indexParaDeletar].getAttribute('value');
if (del[indexParaDeletar].addEventListener) {
del[indexParaDeletar].addEventListener("click",
function() {
confirmaExclusao(id_cliente);
}
);
} else if (del[indexParaDeletar].attachEvent) {
del[indexParaDeletar].attachEvent("onclick",
function() {
confirmaExclusao(id_cliente);
}
);
}
};
var del = document.getElementsByClassName("del");
if (del != null) {
for (var i=0; i<del.length; i++) {
deletar(i);
}
}
I hope I have helped.