当ES6 Arrow函数似乎无法使用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
在对象定义中显式使用arrow函数是可行的,但将Object函数与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
就像概念证明一样,将Template字符串语法与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应该在逻辑上起作用,但是我对输出感到困惑。我猜这是一个范围界定的问题,但是输出“是未定义的”让我望而却步。
隔江千里
弑天下
相关分类