简体   繁体   English

在JavaScript类中混合箭头功能是否有任何弊端?

[英]Are there any drawbacks to mixing arrow functions in javascript classes?

If you aren't familiar the EMCA6 Draft will be adding arrow function syntax . 如果您不熟悉,EMCA6 Draft将添加箭头函数语法 The main differences being: 主要区别在于:

  • Arrow functions have lexical this (so no need to call Function.prototype.bind or create a closure) 箭头函数具有此词法(因此无需调用Function.prototype.bind或创建闭包)
  • Shorter syntax () => "foo" vs function(){ return "foo";} 较短的语法() => "foo" vs function(){ return "foo";}
  • Arrow functions lack a .prototype. 箭头函数缺少.prototype。 So they cannot be used as constructors, cannot be called with new, and are meant to be lightweight. 因此它们不能用作构造函数,不能用new调用,并且它们必须是轻量级的。

With that being said, lets take a look at the following trivial example: 话虽如此,让我们看下面的简单例子:

var Animal = function(sound) {
    this.sound = sound;
    //arrow notation has lexical this, so this makeNoise must be defined in the constructor
    Animal.prototype.makeNoise = () => this.sound;
};

let dog = new Animal("woof!");
dog.makeNoise(); //woof!

Here, I'm creating a simple class that just happens to use a arrow function as one of its methods rather than a normal function. 在这里,我正在创建一个简单的类,该类恰好使用箭头函数作为其方法之一,而不是常规函数。 I know this is setting the Animal.prototype.makeNoise every time we initialize an Animal, but does the above have any other drawbacks compared to the normal: 我知道这是在每次我们初始化Animal时都设置Animal.prototype.makeNoise ,但是与普通方法相比,上述方法还有其他缺点Animal.prototype.makeNoise

var Animal = function(sound) {
    this.sound = sound;
};
Animal.prototype.makeNoise = function() { return this.sound; };

let dog = new Animal("woof!");
dog.makeNoise(); //woof!

I'm curious to see if there any lurking dangers to doing this, as I'm sure people will be tempted to use the new shortened syntax anywhere they can get away with it. 我很想知道这样做是否存在潜在的危险,因为我敢肯定人们会很想在任何可以避免的地方使用新的缩短的语法。 Thanks in advance. 提前致谢。

I'd suggest against doing this, partly for the reason Pointy gave in his comment: you're creating a new arrow function object for every instance of Animal, which is bad for performance and terrible for memory management. 我建议不要这样做,部分原因是Pointy在他的评论中提到:您正在为Animal的每个实例创建一个新的箭头函数对象,这对性能不利且对内存管理不利。 It's actually even worse than just duplicating function objects: since it also creates a new closure around that function, the garbage collector will not be able to free any of your constructor's local variables as long as the animal object is still in memory. 实际上,这甚至比仅复制函数对象还要糟糕:由于它还在该函数周围创建了一个新的闭包,因此只要动物对象仍在内存中,垃圾收集器就无法释放任何构造函数的局部变量。

But also because ECMAScript 6 also introduces a much better syntax for that exact purpose: 也是因为ECMAScript 6为此目的引入了更好的语法:

class Animal {
   constructor(sound) {
       this.sound = sound;
   }
   makeNoise() {
       return this.sound;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM