Wednesday, July 18, 2012

Yet Another Post About JavaScript Scopes and Closures


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


When defining a standalone function (not bound to any object), this is bound to the global namespace. As a direct result, when creating an inner function within a method, the inner function’s this variable is bound to the global namespace, not the method. To circumvent this situation, the enclosing method’s this variable is assigned to an intermediate variable called that, by convention.

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