ES6箭头功能不适用于原型?

Jon*_*cas 23 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
Run Code Online (Sandbox Code Playgroud)

在对象定义中显式使用箭头函数,但使用带有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
Run Code Online (Sandbox Code Playgroud)

正如概念验证一样,使用带有Object.prototype语法的Template字符串语法可以正常工作:

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
Run Code Online (Sandbox Code Playgroud)

我错过了一些明显的东西吗 我觉得示例2应该在逻辑上起作用,但我对输出感到困惑.我猜这是一个范围问题,但我被输出'是一个未定义的'抛弃了.

ES6小提琴

Ami*_*mit 26

箭头功能提供词汇this.它使用在this评估函数时可用的值.

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

(function(this){
   // code that uses "this"
 })(this)
Run Code Online (Sandbox Code Playgroud)

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

在第3个示例中,未使用箭头函数,标准this行为始终有效(函数作用域中的此行为).

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

  • *"箭头函数提供了一个词汇"*更准确的说箭头函数不提供`this`,因此它不是来自它自己的词法范围,而是来自外部词法范围. (4认同)
  • 我认为它更等同于`function(){}。bind(this)`。它预先绑定到创建它的作用域的“ this”。这在事件监听器中很有用,例如,我们经常希望使用监听器内部范围内的东西。在es5代码中,这意味着在附加侦听器或使用“绑定”之前先执行“ var me = this”。 (2认同)

Bas*_*ran 7

常规函数返回对当前 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
Run Code Online (Sandbox Code Playgroud)

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