在IIFE上使用.call(this)

Gre*_*ett 5 javascript

我见过一个IIFE .call(this),而不仅仅是().为什么要这样做?

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

(据我所知,它this会引用window对象 - 无论如何都会调用IIFE.这似乎是多余的.)

ibr*_*rir 5

如果在不使用call的情况下调用IIFE ,则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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

注意:

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


jfr*_*d00 5

这只是将词汇的值传递给thisIIFE 的一种方式- 仅此而言,thisIIFE内部将具有与周围代码相同的词汇值.根据IIFE的位置,this可能不是窗口对象.它可能具有实际的词汇和本地价值.

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

当你传递'this'作为参数时.

为了告诉您有关您的情况的更多信息,我们必须在上下文中查看实际代码.

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