1

var obj = {
  log: function() {
    console.log(this);
    var nestedLog = function() {
      console.log(this);
    }
    nestedLog();
  }
};

obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }

and then i get

{log: ƒ}
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

Can somebody explain me why this binding is gone? I didn't execute nestedLog from global execution context but still i got window object from this binding. I can't really understand why it's happening. I know that this binding depends on execution context and if i do something like this:

var log = obj.log;
log()

it's obvious that i get window object. But when i execute nestedLog inside obj.log function, shouldn't this binding stay the same? Can somebody explain me how does it work?

Ele
  • 31,191
  • 6
  • 31
  • 67
WaBC9IPa
  • 13
  • 2
  • `nestedLog` is just a local variable being executed without a `this`. Unless you call it like this `nestedLog.bind(this)()` or use an arrow function, it'll be window. – adiga Mar 02 '19 at 15:03
  • `nestedLog` is called without any `this` binding. It is not relevant whether it is a local variable or not. It is the way it is called that matters. – trincot Mar 02 '19 at 15:04

1 Answers1

0

log is method of the obj so this is set to obj.

When a function is called as a method of an object, its this is set to the object the method is called on

nestedLog is not a object method so this is set to window object
In simple call of function

this will default to the global object, which is window in a browser.

Use can fix this using Arrow Function

var obj = {
  log: function() {
    console.log(this);
    var nestedLog = () => {
      console.log(this);
    }
    nestedLog();
  }
};

obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51