Clases y métodos estáticos en coffeescript

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


class Box2DUtility

  constructor: () ->

  drawWorld: (world, context) ->



preguntado el 01 de febrero de 12 a las 03:02

1 Respuestas

You can define class methods by prefixing them with @:

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

# And then draw your world...


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

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



Respondido 01 Feb 12, 08:02

haría constructor: (@s) -> also work in the second example? (i.e., instead of the manual assignment @s = s) - Tripp Lilley

@TrippLilley: Yes, you could do it that way if you prefer. - mu es demasiado corto

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); - Sergei Panfilov

@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 no funcionará. - mu es demasiado corto

@AlvaroLourenço Seems that a CoffeeScript class is a "static block" (with some extra stuff): - mu es demasiado corto

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.