One of CoffeeScript's best features is the @
shorthand for this
-- perfect for accessing instance methods and properties:
class Rectangle
constructor: (@width, @height) ->
getArea: ->
@width * @height
But there's no similar shorthand for accessing static members, e.g. @@
. So instead, you're forced to either hardcode class names, or type out the long constructor
reference to be generic:
class BaseView
@TYPE: 'base'
toString: ->
"#{@constructor.TYPE} view"
class ListView
@TYPE: 'list'
Here's a homegrown convention to address this: since class bodies are executable, add a snippet at the bottom of each class (this could be a one-line call or include) that adds instance proxies for static members.
Unfortunately, the @
character isn't allowed in identifiers, but $
is. So this convention simply adds a $
prefix to all proxies. The result:
class BaseView
@TYPE: 'base'
toString: ->
"#{@$TYPE} view"
class ListView
@TYPE: 'list'
The helper code to put at the bottom of class bodies:
for prop of @
proxy = '$' + proxy
Object.defineProperty @::, proxy, do (prop) ->
get: -> @constructor[prop]
set: (val) -> @constructor[prop] = val
Feedback/thoughts/suggestions welcome!
It could be simpler as below:
@$$.TYPE will be clearer than @$TYPE
And this line can be put at the begin of class body, too:
Object.defineProperty @::, '$$', get: ->@constructor