var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
为什么上面这段代码运行之后alert 出来的是“The Window”?? 求详细解释
this对象是在运行时基于函数的执行环境绑定的,
匿名函数的执行环境具有全局性,
因此匿名函数的this指向window
object.getNameFunc()返回的是一个函数,不是object的属性,那么this自然就指向全局上下文了,不是window是嘛
匿名函数里面this==window
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
that = this;
return function(){
return that.name;
};
}
};
alert(object.getNameFunc()()); //The Window
[code="javascript"]
var fn = object.getNameFunc();
alert(fn());
alert(function(){
return this.name;
})
[/code]