An inner function has always access to the outer function's variable and parameters even after the outer function has returned . Lets understood with a simple example,
function retirement(retirementAge){
var a="years left until retirement";
return function(yearOfBirth){//inner function
var age = 2016-yearOfBirth;
console.log((retirementAge-age)+a);
}
}
var retirementUS=retirement(66);
retirementUS(1990);
we already know about lexical scoping , an inner function has access to the variable of the outer function . When a function gets called it is invoked into execution context .Then VO(variable objects) stores the variable, and the scope chain keep track of the variables to use by the function . When a function returned it will popped up from execution context . So the execution context gets cleared .When the inner function invoked then it is gets called into execution context ,then how inner function can access to the outer functions variable . It is possible only for closures.
The scope chain always stays intact .We no need to define closure manually . It is built into javascript. Javascript is always do this for us automatically .
No comments:
Post a Comment