Static classes and methods in coffeescript

Coffeescript

Coffeescript Problem Overview


I want to write a static helper class in coffeescript. Is this possible?

class:

class Box2DUtility
  
  constructor: () ->
    
  drawWorld: (world, context) ->
    

using:

Box2DUtility.drawWorld(w,c);

Coffeescript Solutions


Solution 1 - Coffeescript

You can define class methods by prefixing them with @:

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

# And then draw your world...
Box2DUtility.drawWorld()

Demo: http://jsfiddle.net/ambiguous/5yPh7/

And if you want your drawWorld to act like a constructor then you can say new @ like this:

class Box2DUtility
  constructor: (s) -> @s = s
  m: () -> alert "instance method called: #{@s}"
  @drawWorld: (s) -> new @ s

Box2DUtility.drawWorld('pancakes').m()

Demo: http://jsfiddle.net/ambiguous/bjPds/1/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawn McleanView Question on Stackoverflow
Solution 1 - Coffeescriptmu is too shortView Answer on Stackoverflow