如果您不熟悉,EMCA6 草案将添加 arrow function syntax 。主要区别是:
- 箭头函数具有词法 this(因此无需调用 Function.prototype.bind 或创建闭包)
- 更短的语法
() => "foo"
与function(){ return "foo";}
- 箭头函数缺少 .prototype。因此它们不能用作构造函数,不能用 new 调用,并且应该是轻量级的。
话虽如此,让我们看一下下面的简单示例:
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!
在这里,我创建了一个简单的类,它恰好使用箭头函数作为其方法之一,而不是普通函数。我知道这会在每次初始化 Animal 时设置 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!
我很好奇这样做是否存在任何潜在的危险,因为我确信人们会在任何可以逃脱的地方使用新的缩短语法。提前致谢。
最佳答案
我建议不要这样做,部分原因是 Pointy 在他的评论中给出的原因:你正在为 Animal 的每个实例创建一个新的箭头函数对象,这对性能不利,对内存管理也很糟糕。实际上,这比复制函数对象更糟糕:因为它还围绕该函数创建了一个新的闭包,所以只要动物对象仍在内存中,垃圾收集器将无法释放构造函数的任何局部变量。
而且还因为 ECMAScript 6 还为此目的引入了更好的语法:
class Animal {
constructor(sound) {
this.sound = sound;
}
makeNoise() {
return this.sound;
}
}
关于javascript - 在 javascript 类中混合箭头函数有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19084010/