0

why this syntax outputs this error

  const Player = (name, marker) => {
     this.name = name;
     this.marker = marker;
   };
  const playerOne = new Player("Steve", "Y");
  console.log(playerOne);

 // TypeError: Player is not a constructor

And at the same time writing it in function declaration won't

function Player(name, marker) {
  this.name = name;
  this.marker = marker;
}
const playerOne = new Player("Steve", "Y");
console.log(playerOne);
Joey
  • 121
  • 2
  • 12
  • 2
    The answer is literally in the first few lines of the [arrow functions documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Cerbrus Aug 19 '21 at 13:00
  • 1
    Because arrow functions are different from traditional functions, and one of the ways they're different is that you cannot use them as constructor functions. That's because A) they're specifically designed that way; B) they don't have their own `this`, they close over it, so you couldn't initialize the new object, and C) they're intentionally lighter-weight and don't automatically have a `prototype` property with an empty object assigned to it like traditional functions do. – T.J. Crowder Aug 19 '21 at 13:00
  • TL;RD: Arrow functions don't have a `this` – Cerbrus Aug 19 '21 at 13:00
  • Thanks for the answers guys appreciated. – Joey Aug 19 '21 at 13:02

0 Answers0