JavaScript: closure, local variable, and call
Blogs20132013-06-24
JavaScript: closure, local variable, and call
The follow JavaScript codes have 3 features:
- It is a Closure.
- It uses var _this=this; to define a local variable (using var, so not a global variable)
- It uses call() to control the calling range
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var _this = this;
return function(){
return _this.name + '___' + this.name;
};
}
};
console.log(object.getNameFunc()());
console.log(object.getNameFunc.call(object)());
console.log(object.getNameFunc.call(window)());
console.log(object.getNameFunc.call(undefined)());
console.log(object.getNameFunc.call(document.window)());
console.log(object.getNameFunc.call(this)());The returns:
My Object___The Window My Object___The Window The Window___The Window The Window___The Window The Window___The Window The Window___The Window
