这两种声明原型方法的方法有什么区别?

时间:2021-06-14 21:28:46

I've been writing coffeescript for a little while now and ran into something a bit peculiar.

我已经写了一段时间的咖啡,并且遇到了一些有点奇怪的事情。

Traditionally coffeescript declares all prototype methods individually like such:

传统上,coffeescript单独声明所有原型方法,如:

MyClass.prototype.firstMethod = function(){...};
MyClass.prototype.secondMethod = function(){...};

However, MDN says a better way would be to do this:

但是,MDN说更好的方法是这样做:

(function() {
 this.firstMethod = function(){...};
 this.secondMethod = function(){...};
}).call(MyClass.prototype);

For the source please refer to the very end example of this page.

有关源代码,请参阅本页最后一个示例。

I was under the impression that coffeescript tries to render the best possible javascript. Is one way truly better (or possibly different) than the other or is it simply preference?

我的印象是coffeescript试图渲染最好的javascript。一种方式真正比另一种更好(或可能不同),还是只是偏好?

Thanks for reading!

谢谢阅读!

EDIT: Seems that this question has no real answer and comes down to matter of opinion. I will leave it up for another 2 hours before deleting it. I'd like to thank everyone for their input, it helped me understand this topic better.

编辑:似乎这个问题没有真正的答案,归结为意见问题。在删除它之前,我将再保留2个小时。我要感谢大家的意见,这有助于我更好地理解这个主题。

2 个解决方案

#1


3  

The coffeescript transpiler doesn't render the "best" possible javascript. It just does what the contributors to it want it to do. Also, "best" is a matter of opinion in some cases so there will differences anyway.

coffeescript转换器不会呈现“最佳”可能的javascript。它只是做它的贡献者想要它做的事情。此外,“最佳”在某些情况下是一个意见问题,所以无论如何都会有差异。

#2


1  

This is probably going to get closed due to being argumentative, but from my perspective the second is a nice options when dealing with (and encapsulating) scope. You see a lot of IIFE's so you're not accidentally referencing this in the default (global) scope. In an IIFE you're limiting the opportunity to collide with other module definitions.

这可能会因为争论而被关闭,但从我的角度来看,第二个是处理(和封装)范围时的一个很好的选择。您会看到很多IIFE,因此您不会在默认(全局)范围内意外引用它。在IIFE中,您限制了与其他模块定义发生冲突的机会。

#1


3  

The coffeescript transpiler doesn't render the "best" possible javascript. It just does what the contributors to it want it to do. Also, "best" is a matter of opinion in some cases so there will differences anyway.

coffeescript转换器不会呈现“最佳”可能的javascript。它只是做它的贡献者想要它做的事情。此外,“最佳”在某些情况下是一个意见问题,所以无论如何都会有差异。

#2


1  

This is probably going to get closed due to being argumentative, but from my perspective the second is a nice options when dealing with (and encapsulating) scope. You see a lot of IIFE's so you're not accidentally referencing this in the default (global) scope. In an IIFE you're limiting the opportunity to collide with other module definitions.

这可能会因为争论而被关闭,但从我的角度来看,第二个是处理(和封装)范围时的一个很好的选择。您会看到很多IIFE,因此您不会在默认(全局)范围内意外引用它。在IIFE中,您限制了与其他模块定义发生冲突的机会。