0

I have a code snippet down below.

var obj = {
 name: "Mohit",
 func: function(){
  var self = this;
  (function(){
    console.log(this.name);
    console.log(self.name)
  })()
 }
}

After executing obj.func(), I get the first console.log to be undefined while I get the second one to be Mohit.

Does this mean that an IIFE always binds the this to the global window object?

How defining self to be this is the binding for the IIFE happening to the obj?

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • No, it depends on how you execute it. `(function() {}).call({ hello: "world" })` is an IIFE but `this` would be `{ hello: "world" }` – VLAZ Jun 20 '20 at 14:05
  • https://stackoverflow.com/q/133973/9867451 – ibrahim mahrir Jun 20 '20 at 14:06
  • You can use an arrow function which doesn't have its own `this` so it will use the surrounding `this` – ibrahim mahrir Jun 20 '20 at 14:07
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – VLAZ Jun 20 '20 at 14:11
  • @VLAZ How does declaring var self = this binds the IIFE to the obj context? – Mohit Kamal Jun 22 '20 at 14:49
  • @MohitKamal it doesn't *bind* it, it just ensures that the reference used within is the same as the `this` that is outside. – VLAZ Jun 22 '20 at 14:50

1 Answers1

1

Any function you call without a clear reference for this will have this set to the global object, or in "strict" mode to undefined (which is not the case in your example).

You could explicitly ensure that this is bound to obj if you wanted:

    var obj = {
     name: "Mohit",
     func: function(){
      var self = this;
      (function(){
        console.log(this.name);
        console.log(self.name)
      }).call(this)
     }
    }
    obj.func();

By using .call(this), you provide a value for this inside the called function.

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • So let me get this straight, my code has an IIFE which is getting executed without any context binding. So, in this case, my IIFE will automatically get bound by the global window object? If my IIFE was binded by some context with call or apply, it''s context would be the argument passed in the call/apply? – Mohit Kamal Jun 22 '20 at 14:48
  • 1
    Yes, exactly. Any function, *any* function, that is called without on object reference will have `this` bound to the global object or, in "strict" mode, to `undefined`. Whether it's an IIFE or not does not matter. – Pointy Jun 22 '20 at 16:23