ES6箭头功能在原型上不起作用?

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


森林海
浏览 343回答 3
3回答

隔江千里

箭头函数提供了一个词法this。它使用在this评估功能时可用的。从逻辑上讲,它等效于(以下无效代码,因为您不能使用名为的变量this):(function(this){   // code that uses "this" })(this)在您的第一个示例中,arrow函数在构造函数中,并this指向新生成的实例。在您的第三个示例中,未使用箭头功能,并且标准this行为照常运行(此功能在功能范围内)。在第二个示例中,您使用了箭头函数,但是在评估范围内,它this是全局/未定义的。

弑天下

您可以this在this您打算使用的任何地方使用它。例如,假设你的对象有一个setup()功能,增加了多种功能本身,你会这样称呼它:myObj.setup()。该功能可以使用箭头功能添加所需的功能。另一个更典型的用例是使用需要访问this初始上下文的回调函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript