当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函数是有效的,但不能将Arrow函数与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应该在逻辑上起作用,但是我对输出感到困惑。我猜这是一个范围界定的问题,但输出“是未定义的”使我不满意。
箭头功能提供词法this
。它使用评估功能时可用的this
。
在逻辑上等价于(由于您没有名为this
的变量,因此以下无效代码:]
(function(this){
// code that uses "this"
})(this)
在您的第一个示例中,箭头函数在构造函数中,this
指向新生成的实例。
在您的第三个示例中,未使用箭头功能,并且标准的this
行为始终有效(此功能在功能范围内。)>
在您的第二个示例中,您使用了箭头功能,但是在其求值范围内,this
为全局/未定义。
常规函数返回对当前JavaScript对象的引用,但是箭头函数返回对全局窗口对象的引用。