4

Can anybody tell why the global scope is not applicable in the following case ? Why does the line#6 print undefined ? Shouldn't the outer "this" be available in the inner self-executing function ?

var myObj = {
  test1 : 4,
  func : function(){
    console.log(this.test1); //prints 4
    (function(){
      console.log("From self-executing function : " + this.test1); //prints undefined
    })();
  }
};

myObj.func();

Where as, in the following case the global scope is working fine. test1 declared in outer scope is perfectly available in the inner function.

var test1 = 10;
    (function(){
      console.log("From self-executing function : " + test1); //prints 10
    })();

Can anyone please explain what I am missing to understand here ?

sandy
  • 283
  • 1
  • 7
  • 27
  • Something to do with function in the function, you would need to pass this to the second. Don't know why specifically.. – Matthew Page Jan 20 '19 at 19:31
  • Try `console.log(this)` to see the what's `this` value – FZs Jan 20 '19 at 19:31
  • @FZs ... well tried that and it says "[object Window]" for the "this" inner function but couldn't understand why so ? why the outer scope in this case not active ? – sandy Jan 20 '19 at 19:35
  • You may bind the second function or use an arrow function – Szymon D Jan 20 '19 at 19:37
  • "global scope" != "outer scope". – Bergi Jan 20 '19 at 19:43
  • You call `func` on `myObj`, so `this` is `myObj` in `func`. You call the inner function on nothing, and it's not bound, so in the inner function, `this` is the global `window` object in non-strict mode, or `undefined` in strict mode. – Paul-Louis Ageneau Jan 20 '19 at 19:45

1 Answers1

0

In the inner function, this refers to the global object (if not in strict mode).

You could modify the code like this to achieve the result you expect:

var myObj = {
  test1 : 4,
  func : function(){
    console.log(this.test1);
    var self = this;
    (function(){
      console.log("From self-executing function : " + self.test1);
    })();
  }
};

myObj.func();