Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we create prototypes using ES6 Arrow Functions?

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?

like image 783
Damon Avatar asked Jul 19 '18 07:07

Damon


People also ask

Can we use arrow function with prototype?

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.

What is a reason to not use an ES6 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.

Why can't we use this in arrow function?

Arrow functions don't have the arguments object. Therefore, if you have a function that uses arguments object, you cannot use the arrow function.

Is prototype used in ES6?

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.


1 Answers

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
like image 193
JLRishe Avatar answered Oct 06 '22 00:10

JLRishe