我想在coffeescript中编写一个静态助手类。这可能吗?
类:
class Box2DUtility
constructor: () ->
drawWorld: (world, context) ->
使用:
Box2DUtility.drawWorld(w,c);
最佳答案
您可以通过在类方法前面加上@
来定义类方法:
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/