Here are two different ways of defining a class in Coffeescript:
Both of these define a class called
- a public field
memberinitialized by a constructor parameter
- a private field
- a private method
- a privileged method
- a public method
We can use both in the same way:
The version above on the right is a translation of Douglas Crockford’s pattern, using his example.
Which is better? The left is a bit easier to read for a newcomer to the language, but I find the right more elegant because there is less “magic”.
And there is another advantage to the Crockford style. Consider this small modification:
Here we have generalized the class by adding a
decrementBy parameter to the constructor. We do not copy this to a property, but any of the private or privileged methods in the class can use it. (Don’t you love closures!). There is no way to do this using the Coffeescript
class syntax in a way that would prevent the decrementBy value being modified from outside the object.
I think I might switch to using the Crockford-style classes.