Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of .call(this) on IIFE

Tags:

javascript

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 understand it, this would refer to the window object - which is where the IIFE would be called anyway. It seems redundant.)

like image 604
drenl Avatar asked May 13 '18 02:05

drenl


1 Answers

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);
like image 138
ibrahim mahrir Avatar answered Oct 03 '22 04:10

ibrahim mahrir