coffeescript中的静态类和方法

时间:2012-02-01 03:55:54

标签: coffeescript

我想在coffeescript中编写一个静态助手类。这可能吗?

类:

class Box2DUtility

  constructor: () ->

  drawWorld: (world, context) ->

使用:

Box2DUtility.drawWorld(w,c);

1 个答案:

答案 0 :(得分: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/