1

Consider the following constructor function having a method logging the context

function Foo() {
  this.logContext1 = () => console.log('logContext1', this);
}

let foo = new Foo();

foo.logContext2 = () => console.log('logContext2', this);

foo.logContext1();
foo.logContext2();

logContext1 has context (this) set to the Foo object created by new,

whereas logContext2 has context (this) set to the window object

Considering both are arrow functions, why do we see this difference?

Akshay
  • 63
  • 5

1 Answers1

1

this is defined where the arrow functions are declared:

  • () => console.log('logContext1', this) is declared in the constructor, this is the object being created in that context
  • () => console.log('logContext2', this) is declared on top-level, this is window in that context (or undefined in strict mode)
Guerric P
  • 30,447
  • 6
  • 48
  • 86