86

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);
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

1 Answers1

179

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/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 4
    Would `constructor: (@s) ->` also work in the second example? (i.e., instead of the manual assignment `@s = s`) – Tripp Lilley Jun 05 '13 at 16:28
  • 1
    @TrippLilley: Yes, you could do it that way if you prefer. – mu is too short Jun 05 '13 at 17:19
  • But if we puts methods into 'this', they didn't be truly static anymore, isn't it? Truly static methods should stay in obj.prototype. In example of Shawn Mclean we may call methods like this: Box2DUtility::drawWorld(w,c); – S Panfilov Oct 08 '14 at 08:15
  • 1
    @SergeyPanfilov: But anything in the prototype is also available through `this`, that's just how JavaScript works so you can't do anything about it. We don't really have classes either, just objects, prototypes, and constructor functions so the terminology is even more confused. Attaching functions as properties of the constructor function (which is what's happening here) is the closest equivalent to a class method we have. Check the JavaScript `Box2DUtility::drawWorld` won't work. – mu is too short Oct 08 '14 at 18:10
  • @SergeyPanfilov: Here's a simplified version of the structure [at coffeescript.org](http://coffeescript.org/#try:class%20C%0A%20%20im%3A%20-%3E%0A%20%20%40cm%3A%20-%3E%0A%0Aconsole.log%20C.cm%0Aconsole.log%20C%3A%3Acm). – mu is too short Oct 08 '14 at 18:11
  • Is there a way to execute `static blocks` in Coffeescript classes? – Alvaro Lourenço Oct 12 '17 at 03:06
  • @AlvaroLourenço Sorry, not quite sure what you're asking. – mu is too short Oct 12 '17 at 06:09
  • Something like https://stackoverflow.com/questions/2420389/static-initialization-blocks – Alvaro Lourenço Oct 12 '17 at 06:17
  • 1
    @AlvaroLourenço Seems that a CoffeeScript class is a "static block" (with some extra stuff): https://jsfiddle.net/ambiguous/ap72ckax/ – mu is too short Oct 12 '17 at 17:59
  • Maybe it's just me but I find this syntax very scary. Might make sense if you stay in coffeescript world but it doesn't translate very well in JS. – micky2be Nov 16 '17 at 01:48