47

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

ES6 小提琴

4

2 回答 2

46

箭头函数提供了一个词法this. 它使用在this评估函数时可用的 。

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

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

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

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

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

于 2015-07-31T21:13:50.027 回答
4

常规函数返回对当前 JavaScript 对象的引用,而箭头函数返回对全局窗口对象的引用。

常规函数可以很好地处理使用 new 关键字的对象。它们具有构造函数,在对象创建期间可以通过该构造函数初始化值。它可以使用原型链接进行管理,但箭头函数没有构造函数原型链接。它们不能很好地处理对象。它们不能与 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

参考:常规功能和方向键功能的区别

于 2020-04-06T18:18:51.683 回答