coffeescript中的多个构造函数

Sha*_*ean 2 coffeescript

当我尝试在咖啡脚本中编写多个构造函数时,我得到了这个错误:cannot define more than one constructor in a class.

我怎样才能做到这一点:

class Vector2
  x: 0
  y: 0

  constructor:() ->

  constructor:(@x, @y) ->

  constructor:(vector) ->
     x = vector.x
     y = vector.y
Run Code Online (Sandbox Code Playgroud)

我想要一个空的构造函数和另外两个构造函数.这可能吗?

isl*_*205 11

简单地用coffeescript方式做到这一点:

class Vector
  constructor:(@x=0,@y=0) ->
      if typeof @x is "object"
        vector=@x
        @x=vector.x
        @y=vector.y

###
test start
###
v=new Vector()
console.log v.x,v.y
v=new Vector(1,1)
console.log v.x,v.y
v=new Vector {x:1,y:1}
console.log v.x,v.y
###
test end
###
Run Code Online (Sandbox Code Playgroud)