coffeescript中的静态类和方法

Sha*_*ean 86 coffeescript

我想在coffeescript中编写一个静态帮助器类.这可能吗?

类:

class Box2DUtility

  constructor: () ->

  drawWorld: (world, context) ->
Run Code Online (Sandbox Code Playgroud)

使用:

Box2DUtility.drawWorld(w,c);
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 179

您可以通过为它们添加前缀来定义类方法@:

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

# And then draw your world...
Box2DUtility.drawWorld()
Run Code Online (Sandbox Code Playgroud)

演示: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()
Run Code Online (Sandbox Code Playgroud)

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

  • +1然后'然后画出你的世界......'评论 (6认同)
  • `constructor:(@ s) - >`也适用于第二个例子吗?(即代替手动分配`@s = s`) (4认同)