我想在coffeescript中编写一个静态助手类。这可能吗?
类:
class Box2DUtility
constructor: () ->
drawWorld: (world, context) ->
使用:
Box2DUtility.drawWorld(w,c);
答案 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()