0

"this" gives myCar object reference inside logColor function but gives window object reference inside the func function why?

var myCar = {
    color: "Blue",
    logColor: function() {
        var self = this;
        console.log("In logColor - this.color: " + this.color);
        console.log("In logColor - self.color: " + self.color);
        var func=function() {
            console.log("In IIFE - this.color: " + this.color);
            console.log("In IIFE - self.color: " + self.color);
        }
       func();
    }
};
 
myCar.logColor();

This may not make sense expert javascript developer but my basics are pretty shaken

Shubham
  • 189
  • 9
  • `"this" refers to the current object it is inside` No, it refers to the *calling context* of the function. eg `myfunc.logger()` -> calling context is `myfunc`, but `const someFunc = myfunc.logger; someFunc();` -> calling context is global/undefined – CertainPerformance May 25 '18 at 02:05

1 Answers1

0

You can use the ES-6 Fat Arrow Notation to accomplish your task. This happens becaus einside a closure in an object this always points to global scope.

var myCar = {
    color: "Blue",
    logColor: function() {
        var self = this;
        console.log("In logColor - this.color: " + this.color);
        console.log("In logColor - self.color: " + self.color);
        var func=() => {
            console.log("In IIFE - this.color: " + this.color);
            console.log("In IIFE - self.color: " + self.color);
        }
       func();
    }
}
Abhisar Tripathi
  • 1,569
  • 10
  • 21