I’m reading through the spine.js documentation and I’m wondering a little bit about the function declarations.
In the doc i always read
constructor: ->
super
....
But otherwise i always read
constructor = ->
super
....
So are : and = equal for function declarations?
No.
When defining a class, the
:works slightly differently than it does elsewhere. In a class definition the:means to put this function as a method on the prototype (instance method).constructor:is a special case to be used for the constructor function.The difference is obvious if you look at the compiled javascript.
compiles to this (Good!)
You can see the constructor is the constructor, and the method is on the prototype.
However, when you use
=you simply assign local variables and the functions are not really part of the class as the constructor or the prototype:Compiles to this (Bad!)
Many issues about coffee script syntax can be discovered or resolved by simply looking at the compiled result. And this also why I do not recommend learning coffee script without also knowing JavaScript, as some of the things that it does for don’t really make sense if you dont know what it compiles into.