frezng
Last Updated: February 25, 2016
·
7.634K
· namuol
4ff020826d61a6cfd875cb5cc29e5ce6

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

Say Thanks
Respond

6 Responses
Add your response

7270
8c37813d0d533bedba6cc7bb8b77eea9

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
4ff020826d61a6cfd875cb5cc29e5ce6

@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
8c37813d0d533bedba6cc7bb8b77eea9

Ahhh that makes sense. Thanks!

over 1 year ago ·
14708
Cedd083dcd1ff5cadc0c14bf96464590

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

over 1 year ago ·
14718
4ff020826d61a6cfd875cb5cc29e5ce6

@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
9b5f437cf749be85e12537f2cd0b5ffd

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

over 1 year ago ·