当ES6箭头函数似乎不适用于使用prototype.object将函数赋值给对象时.请考虑以下示例:
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
Run Code Online (Sandbox Code Playgroud)
在对象定义中显式使用箭头函数,但使用带有Object.prototype语法的箭头函数不会:
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
Run Code Online (Sandbox Code Playgroud)
正如概念验证一样,使用带有Object.prototype语法的Template字符串语法可以正常工作:
function Animal3(name, type){
this.name = name;
this.type = type;
}
Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;}
var myPet3 …Run Code Online (Sandbox Code Playgroud)