为什么this指向死window而不是object
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
console.log(object.getNameFunc());
//输出 this Windowvar name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
console.log(object.getNameFunc());
//输出 this Window2019-08-04
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
console.log(object.getNameFunc());楼主你漏了一个括号,应该是object.getNameFunc()().可以等同于一个函数表达式,即
var fun = object.getNameFunc();这里返回一个函数声明:
function(){
return this.name;
}
fun();最后再调用fun();返回this.name
当函数并非作为一个对象的属性而是被调用时,this被绑定到全局变量,即指向window。所以这里返回的this.name 不是对象中的name,而是window中的全局变量name,即The window。
举报