The documentation explain how to extend a class
class Zebra extends Animal
...
But how do I extend multiple classes? The following does not work
class Sidebar extends Controller, EventEmitter
...
But I wish it did. The JavaScript behind this is more than able to extend any number of classes using the __extend
function, but is there a way to do it in coffee-script?
No, in JavaScript, a class cannot extend from multiple classes, which is also known as “multiple inheritance”. In JavaScript, objects can only be associated with a single prototype, and extending multiple classes would mean that an object associates with multiple prototypes, which is not possible.
Install the “extends-classes” Package By default, each class in Node. js can extend only a single class. That means, to inherit from multiple classes, you'd need to create a hierarchy of classes that extend each other.
Guess I'll just answer my own question. The way I ended up handling this is extending all my classes from a class I call "SuperClass" (the name doesn't matter). From that class I can extend any number of classes. Anyway the class looks like this
moduleKeywords = ['included', 'extended']
class SuperClass
@include: (obj) ->
throw('include(obj) requires obj') unless obj
for key, value of obj.prototype when key not in moduleKeywords
@::[key] = value
included = obj.included
included.apply(this) if included
@
Pretty much just stole it from Spine. An example of a class extended from SuperClass:
class Sidebar extends SuperClass
# Include some other classes
@include Controller
@include EventEmitter
###
Constructor function
###
constructor: ->
# Call extended constructors
Controller.call @
EventEmitter.call @
console.log 'Sidebar instantiated'
Notice that to call the inherited class' constructor the class function is called with @
/this
as context. I haven't needed to extend class functions yet, but I imagine it's very similar to calling the parent constructor:
someFunction: ->
ExtendedClass::someFunction.call @
Please edit this post if I'm wrong. Also please excuse my lack of class inheritance terminology - I'm no expert
Update: One could also define a constructor for SuperClass that automatically called the constructor for all included classes on instantiation. That way you'd just need to call super()
from the subclass. I haven't bothered with that though
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With