anhldbk anhldbk - 1 year ago 79
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download