2

Learning about this in JavaScript. I am confused about the scope of this inside iife. Why this points to window object inside iife? This should points to myObj because it is inside myObj.

window.foo = "bar1";
var myObj = {
   foo: "bar2",
   func: function() {
       var self = this;
       console.log(this.foo + ", " + self.foo);
       (function xx() {
           console.log(this.foo + ", " + self.foo)
       }());
   }
}
myObj.func();

Output -

bar2, bar2
bar1, bar2

I am concerned about bar1 in second line.

Nisarg
  • 13,121
  • 5
  • 31
  • 48
Cheezy Code
  • 1,565
  • 1
  • 11
  • 17
  • 2
    `this` will be `window`, correct. You're not in strict mode and you're not executing the IIFE with any context, so `this` defaults to `window`. – VLAZ Dec 27 '19 at 12:10

1 Answers1

1

Function xx is called as IIFE, which is a simple function call. As per the spec, in simple function call, the global object (window in browser) is assigned to this.

window.foo = "bar1";
var myObj = {
   foo: "bar2",
   func: function() {
       var self = this;
       console.log(this.foo + ", " + self.foo);
       (function xx() {
           console.log(`this === window :`, this === window);
           console.log(this.foo + ", " + self.foo)
       }());
   }
}
myObj.func();

Reference:

Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Nisarg
  • 13,121
  • 5
  • 31
  • 48