CoffeeScript 中的多个构造函数
当我尝试在咖啡脚本中编写多个构造函数时,出现此错误:无法在类中定义多个构造函数
。
我该怎么做:
class Vector2
x: 0
y: 0
constructor:() ->
constructor:(@x, @y) ->
constructor:(vector) ->
x = vector.x
y = vector.y
我想要一个空的构造函数和另外 2 个构造函数。这可能吗?
When I try to write multiple constructors in coffee script, i get this error: cannot define more than one constructor in a class
.
How can I do this:
class Vector2
x: 0
y: 0
constructor:() ->
constructor:(@x, @y) ->
constructor:(vector) ->
x = vector.x
y = vector.y
I want to have an empty constructor and 2 other constructors. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单地用咖啡脚本的方式做到这一点:
simple do that in the coffeescript way:
不,这是不可能的。不过,您可以使用参数对象。只是一个例子,这可能会更好:
这是要求重载功能的票证,没有提交补丁,Ashkenas 关闭了它: https://github.com/jashkenas/coffee-script/issues/531
No it's not possible. You could use the arguments object though. Just an example this could be better:
Here's the ticket asking for overloading functionality, no patch was submitted and Ashkenas closed it: https://github.com/jashkenas/coffee-script/issues/531
更具体地说明为什么这在 JavaScript 中是不可能的,在 CoffeeScript 中也是如此:
JavaScript 不允许重载方法,因为方法只是对象的哈希键(可以是
this
,this 的原型
——或者上下文堆栈对象(如果您使用的是函数表达式)。因此,方法只能通过它们的名称来识别,而不是它们的整个签名(传递的参数或返回值)。因此,同一函数允许您使用arguments
伪数组动态读取实际传递的参数。To be more specific about why this is not possible in JavaScript, and as such in CoffeeScript as well:
JavaScript does not allow overloading of methods, since methods are just hash keys of an object (be it
this
,a prototype ofthis
-- or the context stack object if you are using a function expression). Therefore, methods are identifiable only by their name, not their entire signature (params passed or return value). Because of this, the same function allows you to read the actual passed params dynamically, using thearguments
pseudo-array.正如 JaredMcAteer 所说,多个构造函数在技术上是不可能的,但 island205 的建议达到了相同的效果。
作为另一种选择,如何在多个构造函数中使用具有有意义名称的类方法或普通函数?用你的例子,这个怎么样?
然后你可以像这样使用它:
As stated by JaredMcAteer, multiple constructors are not technically possible, but island205's suggestion achieves the same effect.
As another alternative, how about using class methods or plain functions with meaningful names over multiple constructors? Using your example, how about this?
Then you can use it like this: