Understanding a classic example

So, I was reading this blog about execution context in javascript. After that, I tried to understand a typical example of closure / EC:

http://jsfiddle.net/s3kpmz33/

function foo() {
    var foos = [];
       for(var i = 0; i < 3; i++) {
          foos.push(function() {
             alert(i);
           });
       }
    return foos;
}

var foos = foo();

foos[0]();
foos[1]();
foos[2]();

//All alert 3 

      

I think that if I understood this correctly i

is 3 because of the closure. During the execution of the functions, they will go out of their current scope in scope foo

to find the variable i, and they will find it 3 by the time they execute.

Then I fixed it like this:

http://jsfiddle.net/s3kpmz33/2/

function foo() {
    var foos = [];
       for(var i = 0; i < 3; i++) {
           (function bar(k) {
               foos.push(function _bar() {
                  alert(k);
               })
           })(i);
       }
    return foos;
}

var foos = foo();

foos[0]();
foos[1]();
foos[2]();

//Correctly alert 0, 1, 2

      

Now I believe the reason for this is because every function _bar

now accesses the function scope bar

, and BECAUSE it was iife or any function that will execute with the value I want (a previously declared function like @Quentin pointed out) , they all created their OWN local copy of the value i

and assigned it to a local variable k

.

Am I correct in my assumption? I realize that I may not have explained this very clearly because I don't feel like I understand it well enough. If I have made a mistake in my reasoning, please correct me.

If you could improve my reasoning in simpler terms, it would also be very helpful for me and any programmers who come here looking for answers.

+3


source to share


1 answer


BECAUSE it was iife

It doesn't have to be IIFE. You could call the previously declared function.

function alerter_factory(value_to_alert) {
  return function() {
    alert(value_to_alert);
  }
}

function foo() {
  var foos = [];
  for (var i = 0; i < 3; i++) {
    foos.push(alerter_factory(i));
  }
  return foos;
}

var foos = foo();

foos[0]();
foos[1]();
foos[2]();
      

Run codeHide result




they all created their OWN local copy of i and assigned it to local variable k.

Close.

They have their own local copy of value that was in i

, assigned to the local variable k

.

+3


source







All Articles