当 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 应该在逻辑上工作,但我对输出感到困惑。我猜这是一个范围界定问题,但我对输出“未定义”感到失望。