Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending multiple classes in coffee-script

Tags:

coffeescript

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?

like image 755
Hubro Avatar asked Jan 30 '12 13:01

Hubro


People also ask

Can you extend multiple classes in JavaScript?

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.

How do I extend multiple classes in node JS?

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.


1 Answers

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

like image 78
Hubro Avatar answered Oct 14 '22 20:10

Hubro