例子来源http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html
例一
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
例二
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
alert(object.getNameFunc()());//My Object
- 函数中的this指的是调用这个函数的owner
- object.getNameFunc()是返回一个函数,并没有执行函数中的代码
例一做如下改动
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name; //这个this是有上下文的限制的
};
}
};
var tmp = object.getNameFunc(); //此时没有执行this.name
var name = tmp();//这个时候才执行,这时候的this上下文为全局
alert(name);//The Window
例二做如下改动
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
var tmp = object.getNameFunc(); //这个时候执行了that = this,这里的this上下文是object,所以that指的是object
var name = object.getNameFunc(); //这个时候执行了that.name
alert(name);//My Object
网友评论