anhldbk anhldbk - 21 days ago 5
Javascript Question

Confused about arrow functions

would you please tell me what's wrong with snippet 1? My expected output for obj.discover() is 3. How can't I bind

this
to an arrow function method of an object?

'use strict'

// Snippet 1
var obj = {
data: 3,
discover: () => {
return this.data
}
}
obj.discover() // -> undefined
obj.discover.bind(obj)() // undefined

// but if I don't use the arrow notation, everything works
// Snippet 2
var obj2 = {
data: 3,
discover: function(){
return this.data
}
}
obj2.discover() // -> 3

Answer

Arrow functions are not just a syntactic sugar but differ in some behaviour as well. In arrow functions, this always point to the object at which it was pointing at the time of function definition.