【问题标题】:Does an IIFE's this always point towards the global object?IIFE 的 this 是否总是指向全局对象?
【发布时间】: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


【解决方案1】:

在没有明确引用 this 的情况下调用的任何 函数都会将 this 设置为全局对象,或者在“严格”模式下设置为 undefined(在你的例子)。

如果需要,您可以明确确保 this 绑定到 obj

    var obj = {
     name: "Mohit",
     func: function(){
      var self = this;
      (function(){
        console.log(this.name);
        console.log(self.name)
      }).call(this)
     }
    }
    obj.func();

通过使用.call(this),您可以在被调用函数内为this 提供一个值。

【讨论】:

  • 所以让我直说吧,我的代码有一个 IIFE,它在没有任何上下文绑定的情况下执行。那么,在这种情况下,我的 IIFE 会自动被全局窗口对象绑定吗?如果我的 IIFE 被某些上下文与 call 或 apply 绑定,那么它的上下文将是 call/apply 中传递的参数?
  • 是的,完全正确。任何在没有对象引用的情况下调用的函数,any 函数,都将this 绑定到全局对象,或者在“严格”模式下,绑定到undefined。是否是 IIFE 并不重要。
猜你喜欢
  • 2013-12-30
  • 2020-04-14
  • 2016-07-08
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多