CoffeeScript does have support for classes though - that is to say,
This CoffeeScript ‘class’
Let’s add some inheritance to our CoffeeScript ‘class’.
extend function. There are 2 types of methods that need to be inherited from the parent - methods defined on the parent itself (we can think of these as class methods) and methods defined on the prototype of the parent (we can think of these as instance methods).
A special constructor function (called
ctor) is then created to act as the prototype of the child class. CoffeeScript does a lot of work here just to enable us to call
super when we override parent methods in the child. (
super is treated as a keyword and CoffeeScript does some additional magic in order to make it all work)
ctor function - because they’re both just objects. Any new instances of the child class will also have the same prototype and because the
ctor function has the parent class as a prototype we are effectively using normal prototypal inheritance with an additional level of indirection - all to enable calls to
super (which is actually really useful).
extend function that CoffeeScript uses for inheritance, copying functions between classes is actually rather easy.
I’m referring to the first part of the
Let’s look at how we might implement mixins in CoffeeScript:
Within the Employee class (function) I am simply looping through all the properties on the Manager class (function) and assigning them to the prototype of the Employee class.
This might seem strange until you consider that this is exactly how we have been declaring methods on classes all along!
In this example the
This is equivalent to how I am assigning the mixin methods - this piece of CoffeeScript:
So this pattern really allows us to assign methods to our ‘class’ in exactly the same way as we did before. The only difference is that our Manager ‘class’ (in Ruby we would call this a module) assigns functions directly to the Manager ‘class’, instead of to the propotype. This makes perfect sense, since we don’t necessarily want to have to create an instance of the Manager ‘class’ in order to use it as a mixin in the Employee ‘class’.
Why do we need Mixins?
I started playing around with mixins in CoffeeScript because I became frustrated with sharing code via inheritance. When the only way to share code between classes is inheritance, you can easily end up with inheritance where it doesn’t really make sense. (When all you have is a hammer, everything looks like a nail!)
This pattern would at the very least provide an alternative to inheritance - which is clearly not always the best solution. You can find all the code on Plunker. Happy coding.