0

i have this code and this is working:

 var wrap_inner = document.getElementsByClassName("wrapper"),
 base_icon = document.getElementsByClassName("inner");
 function fx_effect () {
    for (var i = 0; i < wrap_inner.length; i++) {
       (function (index) {
        wrap_inner[i].addEventListener('click',function() {
        base_icon[index].classList.toggle('tc');
        });
       })(i); <==== what is that? what do that?
    }
}fx_effect();

but i don't know what is the index in: function (index) { ... and what is (i) at the end of function. Why index is used? What is its value?

why (i) at the end of function used like this? When should be used in this way?

why the function like this don't work???:

 function fx_effect () {
    for (var i = 0; i < wrap_inner.length; i++) {
        wrap_inner[i].addEventListener('click',function() {
        base_icon[i].classList.toggle('tc');
        });
    }
}fx_effect();

I'm confused :(

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
sina
  • 181
  • 1
  • 12
  • See also: http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – Steve's a D Sep 16 '16 at 16:34
  • "*why (i) at the end of function*" - That's how you call a function in JS. Also see the possible duplicate [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/1529630) – Oriol Sep 16 '16 at 16:39

1 Answers1

0

The concept is javascript closures . First method is creating a closure ( a scope or a stack as analogy) for each value passed. So that when fx_effect is called, the inner method runs for values 0 to wran_inner.length distinctively as each value is in a different closure.

For second method, the scope will have just the final value, hence calling the method fx_effect will result in the loop running that method for final value of i, i.e. wrap_inner.length - 1

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175