在IIFE上使用.call(this)

时间:2018-05-13 02:24:18

标签: javascript

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

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

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

2 个答案:

答案 0 :(得分: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);

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 1}}(它们不绑定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);):

this

答案 1 :(得分:5)

这只是将词汇this的值传递给IIFE的一种方式 - 只不过是IIFE中的this将具有与周围代码相同的词汇值。根据IIFE的位置,.call(this)可能不是窗口对象。它可能具有实际的词汇和本地价值。

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

When you pass 'this' as an argument

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

在您添加链接的特定代码中,我没有看到任何特定原因,因为我在IIFE的顶层没有看到case class HotSauce(amount : Double, capcaisin : Double) class SpicyMeatball extends Actor { override def receive: Receive = { case HotSauce => // How do I get access to the HotSauce message instance? val capcaisin = ???.getCapcaisin() } } 的任何引用。它似乎只是一种通常使用的编码习惯,在某些情况下很有用,但在其他情况下则不需要或有用。