First, I create a ES5 Function and then create it's prototype:
var Person = function() {};
Person.prototype.city = function() {return 'New York'}
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?
Share Improve this question asked Jul 19, 2018 at 7:12 AxelAxel 5,12118 gold badges75 silver badges146 bronze badges 5 |1 Answer
Reset to default 21Because 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
new
. – Felix Kling Commented Jul 19, 2018 at 12:13