2

I assigned my arrow function to outside variable.But I did not understand why this is refer to 'Animal' constructor. When I called function 'fun' it printed 'Animal, true'. But I thought it would print 'Window, false'.

function Animal() {
  this.sleep = () => {
    console.log(this, this instanceof Animal)
  }
}

let animal = new Animal();
animal.sleep(); // Animal, true

let fun = animal.sleep
fun = animal.sleep;
fun() // Animal, true -- why?
adiga
  • 34,372
  • 9
  • 61
  • 83
Tamerlan
  • 119
  • 1
  • 5

1 Answers1

2

Arrow functions resolve this lexically, just like any other variable. That means the value of this does not depend on how the function is called, but how/where it was defined.

The sleep function is defined inside the Animal constructor function, which is called with new. Therefore this will refer to a new instance of Animal.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143