What happens in this case is the following:
- Within the scope of
for
there is the variable i
, which is initialized in 0
and increased with +1
every "turn" that occurs because of the loop of repetition for
- Also within the scope of
for
a anonymous function that receives the parameter that was also called i
by simple chance of fate, which, could be called anything, could be for example (funciontion(meuParametroMuitoLouco) { ...
- From there, the variable
i
within the anonymous function becomes the received parameter in the function, not the variable i
of for
- About the command in brackets
(i)
at the end of anonymous function what it does is simply perform the function that has just been created anonymously by passing the variable i
established in the method declaration for
The reason you don’t understand what happens is precisely because of the choice of variable names, which makes very confusing the visual separation of the code, an alternative is to change the name of the received variable as parameter within the anonymous function, as an example 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, making the function not anonymous, which has the benefit of assisting 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’ve helped.
An abridged way of saying what this is is: It’s a self-execution function. It creates a closed scope. That is why when you remove the variable 'i' it generates an error. A while ago I asked a similar question, there are some nice links in my question and in the answers. At a glance: http://answall.com/questions/150775/best-forma-de-utilizar-module-pattern-em-javascript
– alan
It is answered here on the website: http://answall.com/questions/23785/
– Bacco
Thank you guys, you both gave me a light. But what killed my doubt in fact was this article I found: https://goo.gl/CYsFsw. I leave it there as a reference for those who need it in the future. Big hug!
– Breno Cupertino