frezng
Last Updated: February 25, 2016
·
8.683K
· 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: ->
    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'

6 Responses
Add your response

7270

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 ·
7271

@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 ·
7272

Ahhh that makes sense. Thanks!

over 1 year ago ·
14708

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

over 1 year ago ·
14718

@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 ·
17196

Works fine for me...http://jsfiddle.net/5fsnh76L/

over 1 year ago ·