【发布时间】:2020-06-20 14:00:46
【问题描述】:
我在下面有一个代码 sn-p。
var obj = {
name: "Mohit",
func: function(){
var self = this;
(function(){
console.log(this.name);
console.log(self.name)
})()
}
}
执行 obj.func() 后,第一个 console.log 未定义,而第二个为 Mohit。
这是否意味着 IIFE 总是将 this 绑定到全局窗口对象?
如何定义 self 是发生在 obj 上的 IIFE 的绑定?
【问题讨论】:
-
不,这取决于你如何执行它。
(function() {}).call({ hello: "world" })是 IIFE,但this将是{ hello: "world" } -
您可以使用没有自己的
this的箭头函数,因此它将使用周围的this -
这能回答你的问题吗? How does the "this" keyword work?
-
@VLAZ 声明 var self = this 如何将 IIFE 绑定到 obj 上下文?
标签: javascript function ecmascript-6 ecmascript-5 iife