ES6 箭头函数不适用于原型?

ES6 arrow functions not working on the prototype?

当 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 应该符合逻辑,但我对输出感到困惑。我猜这是一个范围问题,但我被输出 'is a undefined'.

吓到了

ES6 Fiddle

箭头函数提供词法this。它使用在计算函数时可用的 this

它在逻辑上等同于(以下不是有效代码,因为您不能有一个名为 this 的变量):

(function(this){
   // code that uses "this"
 })(this)

在您的第一个示例中,箭头函数在构造函数中,this 指向新生成的实例。

在您的第 3 个示例中,未使用箭头函数并且标准 this 行为一如既往地工作(函数范围内的 this)。

在你的第二个例子中,你使用了一个箭头函数,但在它被评估的范围内,this 是全局的/未定义的。

常规函数returns对当前JavaScript对象的引用,但箭头函数returns对全局window对象的引用。

常规函数可以很好地处理使用 new 关键字的对象。它们具有 constructor 函数,通过该函数可以在对象创建期间初始化值。它可以使用 原型链接 来管理,但是箭头函数没有 构造函数,原型链接 。他们不能很好地处理对象。它们不能与new关键字一起使用来分配内存。

在您的第一个示例中,您在常规函数中编写箭头键函数,然后您将获得输出。

function Animal2(name, type){
    this.name = name;
    this.type = type;
}
Animal2.prototype.toString = function(){
    return () => `${this.name} is a ${this.type}`;
}

var myPet2 = new Animal2('Noah', 'cat');
console.log(myPet2.toString()()); //Noah is a cat

参考:Difference between regular function and arrow key function

箭头函数没有自己的 this ,它解析为最接近函数的 this:

  • 您的第一个示例:this 解析为 Animal() 函数的 this
  • 你的第二个例子:this解析为全局对象window(因为它不在任何函数中)
  • 你的第三个例子:this 因为没有使用箭头函数,所以工作正常。