ES6 箭头函数在原型上不起作用? [英] ES6 arrow functions not working on the prototype?
问题描述
当 ES6 箭头函数似乎不适用于将函数分配给具有原型对象的对象时.考虑以下示例:
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
作为概念证明,使用模板字符串语法和 Object.prototype 语法确实有效:
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
我是否遗漏了一些明显的东西?我觉得示例 2 应该合乎逻辑地工作,但我对输出感到困惑.我猜这是一个范围问题,但我被输出未定义"所抛弃.
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'.
推荐答案
箭头函数提供了一个词法this
.它使用在评估函数时可用的 this
.
Arrow functions provide a lexical this
. It uses the this
that is available at the time the function is evaluated.
它在逻辑上等价于(以下不是有效代码,因为你不能有一个名为 this
的变量):
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)
在您的第一个示例中,箭头函数位于构造函数中,并且 this
指向新生成的实例.
In your 1st example the arrow function is within the constructor, and this
points to the newly generated instance.
在您的第三个示例中,没有使用箭头函数,标准的 this
行为一如既往(函数作用域中的 this).
In your 3rd example, an arrow function isn't used and standard this
behavior works as always (the this in the function scope).
在你的第二个例子中,你使用了一个箭头函数,但在它被评估的范围内,this
是全局的/未定义的.
In your 2nd example, you use an arrow function but at the scope it's evaluated, this
is global / undefined.
这篇关于ES6 箭头函数在原型上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!