So I was reading this blog about the execution context in javascript. After it I tried to understand a typical closure/EC example:
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 closures. At the time the functions will execute they will look outside their current scope, in foo's scope, to find the variable i, and they find that it's 3 by the time they get executed.
I then fixed it this way:
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 that the reason behind this is because every _bar function now looks to the bar function scope, and BECAUSE this was an iife, or any function that would get executed with the value I want (previously declared function for example as @Quentin pointed out), they all created their OWN local copy of the value of i and assigned it to the local variable k.
Am I correct in my assumption? I realize I may not have explained it very clearly, because I don't feel like I understand it well enough. If I made a mistake in my reasoning, please correct me.
If you could improve my reasoning in more simple words, this would also be much appreciated for me and any fellow programmers who come here looking for answers.
BECAUSE this was an iife
It doesn't need to be an IIFE. You could have called a previously declared function instead.
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]();
they all created their OWN local copy of i and assigned it to the local variable k.
Close.
They have their own local copy of the value that was in i assigned to a local k variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With