How does this function work within for?

Asked

Viewed 104 times

0

var del = document.getElementsByClassName("del");
if (del != null) {
    for (var i=0; i<del.length; i++) {
    (function(i) {
      var id_cliente = del[i].getAttribute('value');
      if (del[i].addEventListener) { del[i].addEventListener("click", function(){confirmaExclusao(id_cliente);}); }
      else if (del[i].attachEvent) { del[i].attachEvent("onclick", function(){confirmaExclusao(id_cliente);} ); }
        }
    )(i);
    }
}

I am learning to program, and studying this code I found on the Internet, to delete data in the Database with Javascript and PHP I came across something unknown to me until then. Within the for has a function that is between parentheses, and when finishing this function, there is the variable i of for between parentheses >)(i);<

What does that mean?
Within my program, if I remove this variable (i) or remove the parents of function, function ceases to function. But I cannot understand what or what the purposes of these artifacts are (function within parentheses and (i)) in the Javascript code.

  • 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

  • 1

    It is answered here on the website: http://answall.com/questions/23785/

  • 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!

2 answers

1

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.

  • I do not know if I understand your question, but the purpose of creating a separate function, calling deletar, for example, it is precisely that it is not anonymous, nor that it has a "closed" scope within the execution of the for, so that it is not reusable by other methods that are at the same "level" of for. Therefore, anonymous function is different from closed scope. I do not know if I answered your question. If I couldn’t answer, can you ask otherwise?

  • I removed it to avoid complicating the comments space, but it’s basically the example fiddle @Sergio posted here : http://answall.com/questions/23785/

  • I get it, I liked @Sergio’s reply, if you want to remove that explanation from me down here, for the same reason that you removed your question, that’s fine by me :)

0

The loop for(;;) does not have its own scope, and because of this this function creates a new scope, re-generating the i as an argument.

The argument i within the scope of that function will remain having the same value, while the value of the i outside scope is being modified by the action of the loop.

The intention is to be able to use the current value of i in loop scopes, without losing the same value when this scope is executed, for example:

var functions = [];

for (var i = 0; i < 5; ++i)
    (function(i){
        functions.push(function() {
            console.log(i);
        });
    })(i);

for (var fnc of functions)
    fnc();

// 0
// 1
// 2
// 3
// 4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.