这种方法行不通:
var myObj = {
name : 'luke',
age : '24',
myFunc: (function() {
console.log(this.name); //returns nothing
}())
};
如果我使用这个:
var myObj = {
name : 'luke',
age : '24',
myFunc: (function() {
console.log(myObj.name); //it works
}())
};
是什么导致第 5 行第一个示例中的“this”失败?
最佳答案
this
的值由 Javascript 解释器根据函数的调用方式而不是声明方式来设置。
在这种情况下,您只是将函数作为普通函数来调用,因此 this
将被设置为全局对象(在浏览器中为 window
)或到 undefined
(严格模式下)。
您声明的这一部分:
(function() {
console.log(this.name); //returns nothing
}())
只是一个普通的 IIFE 函数调用,因此 this
设置为 window
或 undefined
(如果在严格模式下)。
参见this answer了解调用代码控制 this
的五种不同方式的完整说明。
此外,您的 myFunc
属性最终为 undefined
,因为您有一个 IIFE 作为值,但该 IIFE 不返回任何内容,因此返回值为 undefined
因此 myFunc
属性的结果值为 undefined
。
由于您似乎很难理解 IIFE 的工作原理,因此您的代码如下:
var myObj = {
name : 'luke',
age : '24',
myFunc: (function() {
console.log(this.name); //returns nothing
}())
};
评估与此相同:
function aFunc() {
console.log(this.name);
}
var myObj = {
name : 'luke',
age : '24',
myFunc: aFunc()
};
并且,从这里,您应该能够看到 aFunc()
是一个普通的函数调用,它会导致 Javascript 将函数内的 this
设置为 窗口
或未定义
(如果在严格模式下)。
关于javascript - 为什么 'this' 在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32927325/