【问题标题】:Use of .call(this) on IIFE在 IIFE 上使用 .call(this)
【发布时间】:2018-05-13 12:42:32
【问题描述】:

我看到一个 IIFE 使用 .call(this),而不仅仅是 ()。为什么要这样做?

上下文:https://github.com/dmauro/Keypress/blob/development/keypress.js

(据我了解,this 将引用 window 对象 - 无论如何都会调用 IIFE。这似乎是多余的。)

【问题讨论】:

  • 哎呀,当然。已编辑。

标签: javascript


【解决方案1】:

如果调用 IIFE 时不使用 call,则其中的 this 将引用全局对象 window(或在严格模式下为 undefined)。使用.call(this) 将传递给它在调用时this 所引用的任何内容(无论当前上下文是什么)。例如,您想使用.call(this) 而不是通常调用它() 的情况是在一个类方法中,其中this 将引用该类的实例并且您希望将其传递给您的IIFE:

function A() {
    (function() {
        this.name = "A";                          // "this" is not the instance of the class A
    })();
}

var a = new A;

console.log(a.name);

function B() {
    (function() {
        this.name = "B";                          // "this" is the instance of the class B
    }).call(this);                                // because we explicitly passed it to the IIFE 
}

var b = new B;

console.log(b.name);

注意:

值得一提的是,使用arrow functions,您可以使用封闭执行的this,而不必使用.call(this),因为箭头函数没有自己的this(它们没有绑定this):

function C() {
    (() => {
        this.name = "C";                          // "this"'s value here is whatever value it has outside the IIFE
    })();                                         // no need for .call(this) here
}

var c = new C;

console.log(c.name);

【讨论】:

    【解决方案2】:

    这只是将词法 this 的值传递给 IIFE 的一种方式 - 仅此而已,因此 IIFE 内的 this 将具有与周围代码中相同的词法值。根据 IIFE 所在的位置,this 可能不是窗口对象。它可能有一个实际的词法和本地值。

    如果你不在 IIFE 上使用.call(this),那么this 值将在函数中重置为全局对象(即浏览器中的window 对象)或在严格模式下, this 将在 IIFE 中变为 undefined。 Javascript 根据函数的调用方式重置this 的值。您可以在此答案中看到this 控制的所有六种不同方式:

    When you pass 'this' as an argument.

    要告诉您更多关于您的情况,我们必须在上下文中查看实际代码。

    在您添加链接的特定代码中,我没有看到任何特殊原因,因为我在 IIFE 的顶层没有看到对 this 的任何引用。它似乎只是一种普遍使用的编码习惯,在某些情况下有用,但在其他情况下不需要或有用。

    【讨论】:

    • @GregoryTippett - 我在您链接的代码上添加了一些 cmets。
    猜你喜欢
    • 2013-07-10
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2014-07-29
    • 2013-09-28
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多