Last Updated: February 25, 2016
· namuol

"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: ->

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'

6 Responses
Add your response


Does that actually work? Surely in the method body, @count won't access the class property. Shouldn't it be @constructor.count ?

over 1 year ago ·

@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!

over 1 year ago ·

Ahhh that makes sense. Thanks!

over 1 year ago ·

I think its easier to use
@addWidget in the constructor as addWidget is within the class declaration

over 1 year ago ·

@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.

over 1 year ago ·

Works fine for me...

over 1 year ago ·