coffeescript教學 - coffeescript缺點



靜態類和coffeescript中的方法 (1)

我想在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/ : 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/ : http://jsfiddle.net/ambiguous/bjPds/1/





coffeescript