在coffeescript中的静态类和静态方法

86

我想用coffeescript编写一个静态的帮助类。这是否可行?

class:

class Box2DUtility

  constructor: () ->

  drawWorld: (world, context) ->

使用:

Box2DUtility.drawWorld(w,c);
1个回答

179

您可以通过在方法前加上 @ 来定义类方法:

class Box2DUtility
  constructor: () ->
  @drawWorld: (world, context) -> alert 'World drawn!'

# And then draw your world...
Box2DUtility.drawWorld()

示例:http://jsfiddle.net/ambiguous/5yPh7/

如果希望您的 drawWorld 类似于构造函数,则可以像这样使用 new @

class Box2DUtility
  constructor: (s) -> @s = s
  m: () -> alert "instance method called: #{@s}"
  @drawWorld: (s) -> new @ s

Box2DUtility.drawWorld('pancakes').m()

演示:http://jsfiddle.net/ambiguous/bjPds/1/


4
在第二个例子中,constructor: (@s) ->也可以工作吗?(即,代替手动赋值的 @s = s - Tripp Lilley
1
@TrippLilley:如果你愿意,你可以那样做。 - mu is too short
1
@SergeyPanfilov:但原型中的任何内容也可以通过this访问,这就是JavaScript的工作方式,所以您无法对此进行任何操作。我们实际上也没有类,只有对象、原型和构造函数,因此术语更加混乱。将函数作为构造函数的属性附加(这就是此处发生的事情)是我们拥有的最接近类方法的等效物。检查JavaScript Box2DUtility :: drawWorld 将不起作用。 - mu is too short
有没有一种方法可以在Coffeescript类中执行静态块 - Alvaro Lourenço
1
@AlvaroLourenço 看起来 CoffeeScript 类是一个“静态块”(带有一些额外的内容):https://jsfiddle.net/ambiguous/ap72ckax/ - mu is too short
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接