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?
Arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword. As such, a prototype property does not exist for an arrow function.
An Arrow function should not be used as methods. An arrow function can not be used as constructors. An arrow function can not use yield within its body. Arrow function cannot be suitable for call apply and bind methods.
Arrow functions don't have the arguments object. Therefore, if you have a function that uses arguments object, you cannot use the arrow function.
The prototype property allows you to add properties and methods to any object (Number, Boolean, String and Date, etc.). Note − Prototype is a global property which is available with almost all the objects. Use the following syntax to create a Boolean prototype.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With