ES6 arrows don't work on prototype?

When ES6 Arrow functions fail to assign a function to an object with prototype.object. Consider the following examples:

function Animal(name, type){ this.name = name; this.type = type; this.toString = () => `${this.name} is a ${this.type}`; } var myDog = new Animal('Max', 'Dog'); console.log(myDog.toString()); //Max is a Dog 

Using the arrow function explicitly in the object definition works, but using the arrow functions with the Object.prototype syntax fails:

 function Animal2(name, type){ this.name = name; this.type = type; } Animal2.prototype.toString = () => `${this.name} is a ${this.type}`; var myPet2 = new Animal2('Noah', 'cat'); console.log(myPet2.toString()); //is a undefined 

As a proof of concept, using template string syntax with Object.prototype syntax works:

 function Animal3(name, type){ this.name = name; this.type = type; } Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;} var myPet3 = new Animal3('Joey', 'Kangaroo'); console.log(myPet3.toString()); //Joey is a Kangaroo 

Am I missing something obvious? I feel that Example 2 should work logically, but I am puzzled by the way out. I assume this is a problem, but the output of "this is undefined" discards me.

ES6 Fiddle

+7
javascript prototype ecmascript-6 arrow-functions
source share
1 answer

The arrow functions provide a lexical this . It uses this , which is available during function calculation.

It is logically equivalent (the following code is invalid because you cannot have a variable named this ):

 (function(this){ // code that uses "this" })(this) 

In your first example, the arrow function is inside the constructor, and this points to the newly created instance.

In your third example, the arrow function is not used, and the standard behavior of this works as always (this is in the function area).

In your second example, you use the arrow function, but in the area that he appreciated, this is global / undefined.

+12
source share

All Articles