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());
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());
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());
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
javascript prototype ecmascript-6 arrow-functions
Jonathan lucas
source share