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.)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With