"Static" Methods and Properties in CoffeeScript
CoffeeScript provides a natural shorthand notation for creating "static" methods and properties on a class:
class Widget
@count: 0
@addWidget: -> @count++
constructor: ->
Widget.addWidget()
w = new Widget
w2 = new Widget
w3 = new Widget
console.log Widget.count # "3"
From the CoffeeScript documentation:
Because in the context of a class definition,
this
is the class object itself (the constructor function), you can assign static properties by using
@property: value
, and call functions defined in parent classes:@attr 'title', type: 'text'
Written by Louis Acresti
Related protips
5 Responses
Does that actually work? Surely in the method body, @count won't access the class property. Shouldn't it be @constructor.count ?
@micapam: Look closely: notice the @
in front of the name of addWidget
? That means the function is actually a static member of the Widget
class. More importantly, this
in the context of a static method's body actually refers to the class itself!
An interesting note: In the context of an object's member function, @constructor
would actually be identical to Widget
based on how CoffeeScript implements classes. Try it!
Ahhh that makes sense. Thanks!
@pyros2097 -- nope, that will not work. In the constructor, the value of @addWidget
is undefined, because no method called addWidget
is specified on the Widget
prototype; it is specified on the Widget
object itself; a "static" method.
Works fine for me...http://jsfiddle.net/5fsnh76L/