2

The following object myObj has the same method defined in three different ways (at least I though they were interchangeable), but the method defined with anonymous literal behaves differently:

const myObj = {
  msg: 'dude',
  say1: () => {
    console.log(this.msg)
  },
  say2: function() {
    console.log(this.msg)
  },
  say3() {
    console.log(this.msg)
  }
}

myObj.say1()
myObj.say2()
myObj.say3()

Result:

undefined
dude
dude

Where does this point to from inside say1 ? Why is it different from say2 and say3 ? I am running this in Node.js (v8.4.0).

dzuremar
  • 170
  • 8
  • 1
    Arrow functions automatically bind `this`. So `this` is equal to whatever this was equal to in the surrounding function. – Nicholas Tower Sep 12 '17 at 15:03
  • 2
    You have an arrow function, a regular function, and a method definition. The value of `this` is different in different types of functions, as arrow functions use the `this` value from the surrounding scope. – adeneo Sep 12 '17 at 15:04
  • Thanks, couldn't find the question that would answer this. I completely forgot the phrase "arrow function", that would have made it. – dzuremar Sep 12 '17 at 15:12

0 Answers0