scope of this in self-executing function

62 views Asked by At

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 ?

1

There are 1 answers

0
Paul-Louis Ageneau On

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();