首页 > 解决方案 > 在 IIFE 上使用 .call(this)

问题描述

我已经看到一个 IIFE 被 包裹起来.call(this),而不仅仅是(). 为什么要这样做?

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

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

标签: javascript

解决方案


如果在不使用的情况下调用 IIFE call,则它的this内部将引用全局对象window(或undefined在严格模式下)。Using.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);

笔记:

值得一提的是,使用箭头函数,您可以获得使用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);


推荐阅读