0
 var obj = {count: 0}
 obj.increment =  () => { this.count = this.count +1}
 obj.increment()
 console.log(obj.count)// outputs  "error: Uncaught TypeError: Cannot read property 'count' of undefined"

But

   var obj = {count: 0}
   obj.increment =  function() { this.count = this.count +1}
   obj.increment()
   console.log(obj.count) //outputs correct count 

Why does the arrow function not get reference of this as the object?

1 Answers1

1

To put it bluntly: it simply is that way. Arrow functions do not get a binding to this.

They have a few more limitations and differences to “regular” functions.

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
ethergeist
  • 469
  • 1
  • 10