javascript - ES6 箭头函数在原型(prototype)上不起作用?

标签 javascript prototype ecmascript-6 arrow-functions

当 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

作为概念证明,使用 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 应该符合逻辑,但我对输出感到困惑。我猜这是一个范围问题,但输出“is a undefined”让我感到困惑。

ES6 Fiddle

最佳答案

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

它在逻辑上相当于(以下不是有效的代码,因为您不能拥有名为 this 的变量):

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

在第一个示例中,箭头函数位于构造函数内,并且 this 指向新生成的实例。

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

在第二个示例中,您使用箭头函数,但在其评估范围内,this 是全局/未定义的。

关于javascript - ES6 箭头函数在原型(prototype)上不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31755186/

相关文章:

javascript - Jquery 帧间通信

javascript - Object.defineProperty() vs Object.prototype.property vs Object.property 什么时候用什么?

javascript - 如何告诉 typescript ,那个过程不是未定义的?

javascript - 在不修改递归函数的情况下添加延迟

javascript - ajax函数打不开页面

javascript - 如何将 Jquery/Bootstrap 文件包含到 Webpack/angular2/typescript 堆栈中

javascript - 向 $resource 原型(prototype)添加一个函数

javascript - JavaScript 的原生原型(prototype)何时在同源框架之间共享?

javascript - 按对象数组过滤对象数组 [TypeScript] [ES6]

javascript - 如何将 div 制作成 slider ?