I understand that scope is created when a function is defined. But I am not sure if I comprehend correctly if the variable value (defined in a function & referenced in inner function, aka closure) is captured also when the nested function is defined , Or, when it is executed.
In the well known closure in loop Scenario, the closure seems to capture the "i" value when the loop finishes. Assuming loop through 5 times, then "i" would be 4. Hence "i" would be captured as 4. Therefore it looks like "i" is only captured when nested function is executed?
It would be appreciated if someone can point out where the capture is happening.
Scenario 1
var fnName = function(x){
return function(){ return ++x; }; // (is x value captured here?)
};
var fnName1 = fnName(0);
fnName1(); // x=1 (is x value captured here?)
fnName1(); // x=2
Scenario 2
var fnName = function(){
var x = 0;
return function(){ return ++x; }; // (is x value captured here?)
};
var fnName1 = fnName();
fnName1(); // x=1 (is x value captured here?)
fnName1(); // x=2
Scenario 3
var fnName = function(){
var x = 0;
function runFn(){ return x++; }; // (is x value captured here?)
runFn();
};
fnName(); // x=0
fnName(); // x=0
Answer
The variable is captured when it is declared. The value isn't captured (which is why it can change).
var fnName = function(x){ // Here
return function(){ return ++x; };
};
var fnName = function(){
var x = 0; // Here (but remember that hoisting exists)
return function(){ return ++x; };
};
No comments:
Post a Comment