When discussing scope it’s important to consider where a variable is defi ned as well as its lifetime.Where is the variable accessible? In the case of JavaScript, scope is maintained at the function level,not the block level. Hence, variables defi ned with the keyword var and parameters are visible only inside the function in question.
A nested function has access to its outer function’s variables, except for this and arguments. The mechanism through which a nested function continues to keep the references of its outer function even after the outer function fi nishes execution is called closure. Closures also help to reduce namespace pollution.
Each time an enclosed function is called, a new scope is created, although the code doesn’t change. The following code shows this behavior.
function getFunction(value){
return function(value){
return value;
}
}
var a = getFunction(),
b = getFunction(),
c = getFunction();
console.log(a(0));
0
console.log(b(1));
1
console.log(c(2));
2
console.log(a === b);
false
obj = {};
obj.method = function(){
var that = this;
this.counter = 0;
var count = function(){
that.counter += 1;
console.log(that.counter);
}
count();
count();
console.log(this.counter);
}
obj.method();
1
2
2
0 comments:
Post a Comment