JavaScript: closure and 'this' object
Blogs20142014-04-13
JavaScript: closure and āthisā object
How to use āthisā object in closure function? The following is an example:
var name = "Window Variable";
var obj = {
name : 'Object Property',
getName: function() {
return function() {
return this.name;
};
}
};
obj.getName()(); // "Window Variable"
// The above is not correct, coz in getName() there is no 'name'
// property, so extend to Global variable 'name'.
// 2. use call(), apply() to use 'obj' instead of 'window':
obj.getName().apply(obj); // "Object Property"
obj.getName().call(obj); // "Object Property"
// 3. And use intermediate variable 'that' to remain
// it is accessible in the function range:
var obj1 = {
name : 'Object Property',
getName: function() {
var that = this;
return function() {
return that.name;
};
}
};
obj1.getName()() //"Object Property" 