0

Sorry if this is a silly mistake, I'm rather new to JavaScript.

So I have a key-function pair ('sayHello') inside the object person which returns an interpolated string using a template literal (${}). It works fine when I use the standard function syntax.

let person = {
  name: 'Ava',
  sayHello () {
    return `Hello, my name is ${this.name}.`;
  }
};

console.log(person.sayHello());
// output: Hello, my name is Ava.

However, when I use arrow function syntax with an arrow token, it returns the 'name' value as undefined.

let person = {
  name: 'Ava',
  sayHello: () => {
    return `Hello, my name is ${this.name}.`;
  }
};

console.log(person.sayHello());
// output: Hello, my name is undefined

Does anyone know what the problem is here, even if it is just a syntax error i've made?

Thanks.

Striped
  • 2,544
  • 3
  • 25
  • 31
Fox
  • 13
  • 3
  • 2
    This is one of the gotchas of arrow functions: they don't have a `this`. Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – nvioli Feb 12 '18 at 21:19
  • 1
    In your example, `this` is referring to `window` thus returning `undefined`. – Derek 朕會功夫 Feb 12 '18 at 21:26

1 Answers1

0

arrow function expressions are best suited for non-method functions. They don't have this. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Description

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
samnu pel
  • 914
  • 5
  • 12