Value of this in object's method defined with anonymous function literal

33 Views Asked by At

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).

0

There are 0 best solutions below