tau
tau

Reputation: 6749

CoffeeScript, prototypal inheritance, and constructors

In CoffeeScript, it seems like the superclasses constructor is not called when you instantiate the subclass.

Is there a way around this?

Here is an example:

class A
    element = null

    constructor: ->
        element = document.createElement "div"

    hide: =>
        element.style.display = "none"

class B extends A
    constructor: ->
        @hide() #error!

I would expect the constructor of A to be called first, then B's constructor. If B then calls the hide method, it should hide the element that was created in A's constructor instead of saying that element is null.

Thanks!

Upvotes: 3

Views: 2237

Answers (1)

robkuz
robkuz

Reputation: 9924

I think you need to call super in the Subclass

class A
    element = null

    constructor: ->
        element = document.createElement "div"

    hide: =>
        element.style.display = "none"

class B extends A
    constructor: ->
        super
        @hide() #error!

Upvotes: 5

Related Questions