当 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
在对象定义中显式使用箭头函数是有效的,但使用带有 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
正如概念证明一样,使用模板字符串语法和 Object.prototype 语法确实有效:
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
我错过了一些明显的东西吗?我觉得示例 2 应该合乎逻辑地工作,但我对输出感到困惑。我猜这是一个范围问题,但我被输出“未定义”所抛弃。