0

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
anhldbk
  • 4,559
  • 5
  • 29
  • 37

3 Answers3

3

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.

Falloutcoder
  • 991
  • 6
  • 19
  • 1
    Worth also pointing out that in the OPs case, `this` is the global object when `discover` is created in `obj`. If it were an object created using `new` etc, it'd be fine to use `this` in an arrow function in that way. – James Thorpe Nov 16 '16 at 11:08
  • @JamesThorpe Thank you for your thorough explanation. – anhldbk Nov 16 '16 at 11:28
  • 1
    @dejavu_cmd_delt: Thank you so much. – anhldbk Nov 16 '16 at 11:28
0

Arrow functions don't allow for binding. Check this reference on MDN:

An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target.

Arrow function will resolve the this to its lexical scope.

Divyanshu Maithani
  • 13,908
  • 2
  • 36
  • 47
0

Arrow functions aren't the same as normal functions and shouldn't be used as object methods. They don't bind 'this', among other things. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Paul
  • 35,689
  • 11
  • 93
  • 122