0

I stumbled on a weird scenario where the context this of an instantiated function inside the constructor is different. Any explanation for this behaviour will be greatly helpful.

function Parent() {
  console.log(this);    // Parent {}
  function Child() {
    console.log(this);  // Window
  }
  Child();
}
var p = new Parent();
// Imagine calling the afore-mentioned function within browser globals.

Couldn't grasp the above output why Child function is still pointing to Window instead of Parent. What am i missing here?

Anvesh Checka
  • 3,400
  • 2
  • 19
  • 27
  • 1
    Each function declaration has its own `this` binding. When you call `Child()`, the calling context is the global object (window), not Parent, and so the `Child`'s `this` gets bound to Window. It doesn't use the `this` from its surrounding scope, if you need that behaviour, then you can use an arrow function for `Child()`, as arrow function's don't have their own `this` binding – Nick Parsons Dec 03 '20 at 04:57

0 Answers0