ES6箭头功能不能在原型上工作? [英] ES6 arrow functions not working on the prototype?

查看:134
本文介绍了ES6箭头功能不能在原型上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用prototype.object将ES6 Arrow函数看起来不适用于将对象赋值给一个函数时。请考虑以下示例:

When ES6 Arrow functions don't seem to work for assigning a function to an object with prototype.object. Consider the following examples:

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语法的函数不会:

Using the arrow function explicitly in the object definition works, but using the arrow functions with the Object.prototype syntax does not:

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对象的模板字符串语法语法确实可行:

Just as a proof of concept, using the Template string syntax with Object.prototype syntax does work:

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

我是否缺少一些明显的东西?我觉得这个例子应该是逻辑上的,但我对产出感到困惑。我猜这是一个范围界定的问题,但是我被输出被抛出了'是一个未定义'。

Am I missing something obvious? I feel that example 2 should work logically, but I am puzzled by the output. I'm guessing it is a scoping issue, but I am thrown off by the output 'is a undefined'.

ES6 Fiddle

推荐答案

箭头函数提供一个词汇。它使用在评估函数时可用的这个

Arrow functions provide a lexical this. It uses the this that is available at the time the function is evaluated.

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

It is logically equivalent to (the following isn't valid code since you can't have a variable named this):

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

在第一个例子中,箭头函数在构造函数内,这个指向新生成的实例。

In your 1st example the arrow function is within the constructor, and this points to the newly generated instance.

在第三个示例中,不使用箭头函数,并且标准这个行为始终如一(在函数范围内)

In your 3rd example, an arrow function isn't used and standard this behavior works as always (the this in the function scope).

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

In your 2nd example, you use an arrow function but at the scope it's evaluated, this is global / undefined.

这篇关于ES6箭头功能不能在原型上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆