-2

On access suit or value inside the arrow function the code give following error:

Uncaught ReferenceError: suit is not defined at Object.toString (VM378 script.js:4) at VM429 script.js:7

let card = {
  suit : "Spades",
  value : "Queen",
  toString : () => suit + " of " + card
};

console.log(card.toString());
Tamil Selvan C
  • 18,342
  • 12
  • 44
  • 63

1 Answers1

1

You have to use the card variable in that case, like this:

let card = {
  suit : "Spades",
  value : "Queen",
  toString : () => card.suit + " of " + card.value
};

console.log(card.toString());

That happens because the arrow functions will take the current context (this) and you will not be able to do this.suit. However, if you use the function syntax, you can do:

let card = {
  suit : "Spades",
  value : "Queen",
  toString : function () { return this.suit + " of " + this.value }
};

console.log(card.toString());
Ionică Bizău
  • 93,552
  • 74
  • 254
  • 426