代码片段一:
var name = "The Window";
var object = {
name : "My Object",getNameFunc : function(){
return function(){
return this.name;
};}
};
alert(object.getNameFunc()());
代码片段二:
var name = "The Window";
var object = {
name : "My Object",getNameFunc : function(){
var that = this;
return function(){
return that.name;
};}
};
alert(object.getNameFunc()());
说:
理解最后两个例子:
1 函数中的this指的是调用这个函数的owner
2 object.getNameFunc()是返回一个函数,并没有执行函数中的代码
3 增加一个例子0:
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return (this.name);
}
};
var name = object.getNameFunc();
alert(name);
4 把例子1变成
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);
//alert(object.getNameFunc()())
5 把例子2变成:
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);
//alert(object.getNameFunc()());
文章信息: