Skip to content Skip to sidebar Skip to footer

Use Of .call(this) On IIFE

I've seen an IIFE wrapped up with .call(this), rather than just (). Why would this be done? The context: https://github.com/dmauro/Keypress/blob/development/keypress.js (As I under

Solution 1:

If the IIFE is invoked without using call, the this inside it would refer to the global object window (or undefined in strict mode). Using .call(this) will pass to it whatever this is refereing to at the moment of the call (whatever the current context is). A situation where you want to use .call(this) instead of just calling it normally (), for example, is inside a class method where this will refer to the instance of the class and you want to pass that to your 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);

Note:

It's worth mentioning that with arrow functions you can have the benifit of using the this of the enclosing execution without having to use .call(this) because arrow functions don't have their own this (they don't bind 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);

Solution 2:

It's just a way of passing the value of lexical this into the IIFE - nothing more so that this inside the IIFE will have the same lexical value it had in the surrounding code. Depending upon where the IIFE is, this may not be the window object. It may have an actual lexical and local value.

If you don't use .call(this) on the IIFE, then the this value will be reset in the function to either the global object (which is the window object in a browser) or in strict mode, this will become undefined in the IIFE. Javascript resets the value of this according to how a function was called. You can see all the six different ways that this is controlled in this answer:

When you pass 'this' as an argument.

To tell you more about your situation, we'd have to see the actual code in context.

In the particular code you added a link to, I don't see any particular reason for doing it as I don't see any references to this at the top level of the IIFE. It appears to just be a coding habit that is generally used and is useful in some circumstances, but not needed or useful in others.


Post a Comment for "Use Of .call(this) On IIFE"