16

First, I create a ES5 Function and then create it's prototype:

var Person = function() {};

Person.prototype.city = function() {return 'New York'}

I get no error in here. But when I create the same with ES6 fat arrow function, I get Cannot set property 'city' of undefined:

let Person = () => {};

Person.prototype.city = () => {return 'New York'}

Why is this?

Axel
  • 4,365
  • 11
  • 63
  • 122
  • "Arrow functions do not have a prototype property" --> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Mark Jul 19 '18 at 07:14
  • Possible duplicate of [Why cannot use lambda to define prototype function](https://stackoverflow.com/questions/36234359/why-cannot-use-lambda-to-define-prototype-function) – Mark Jul 19 '18 at 07:16
  • Even you could do this, arrow functions are not *constructable*, i.e. they cannot be called with `new`. – Felix Kling Jul 19 '18 at 12:13
  • 1
    Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/q/34361379/218196) – Felix Kling Jul 19 '18 at 12:14
  • @MarkMeyer No, this is not a duplicate of that question. This one is about attempting to use a prototype on an arrow function and the other is about assigning an arrow function to another function's prototype. – JLRishe Aug 09 '19 at 18:46

1 Answers1

21

Because by definition, arrow functions don't have prototypes. They're designed to be lightweight, without some of the baggage that old-style functions have.

Another likely reason for this is that arrow functions capture the surrounding this rather than having it determined dynamically. So they would serve poorly as constructor functions because the this within them would be referring to the this from the surrounding scope instead of the object being created. (In fact, you can't even use them as constructor functions. JavaScript will throw an error if you try to.)

From MDN:

Use of prototype property

Arrow functions do not have a prototype property.

var Foo = () => {};
console.log(Foo.prototype); // undefined
Community
  • 1
  • 1
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Why so? I mean how these arrow function work actually in the constructor? – Axel Jul 19 '18 at 07:17
  • @Sanjay Just edited my answer. You shouldn't use an arrow function as a constructor. If you need a constructor, use a regular function. – JLRishe Jul 19 '18 at 07:18
  • Thanks for the explanation! Gotcha! – Axel Jul 19 '18 at 07:19
  • 2
    @JLRishe: *"You shouldn't use an arrow function as a constructor."* It's not even possible. Calling an arrow function with `new` throws an error. – Felix Kling Jul 19 '18 at 12:13