0

I have the following code:

const person = {
  name: 'Bob',
  greet: () => {
    console.log(`Hi, my name is ${this.name}`);
  }
};

person.greet();

For some reason, it outputs:

Hi, my name is undefined

I'd expect it to output:

Hi, my name is Bob
Vic
  • 6,156
  • 3
  • 36
  • 49
  • 2
    Why did you expect that? The scope the arrow function binds isn't the object you're creating, `this` is whatever it was *where you're creating it*. – jonrsharpe Jan 21 '18 at 21:18

1 Answers1

2

An arrow function does not have its own this; the this value of the enclosing execution context is used

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Example:

// An arrow function does not have its own this
// this of enclosing context is used
window.something = 'Yo yo yo'; 
const data = {
  something: 'Eduardo Stuart',
  
  arrowPrintName: () => {
    console.log(this.something) // this will print "window.something" instead
  },

  shortPrintName () {
    console.log(this.something) // this will print eduardo stuart
  }
}

data.arrowPrintName();
data.shortPrintName();
Eduardo Stuart
  • 2,679
  • 15
  • 21