Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 719
tau Avatar asked Jul 09 '26 09:07

tau


1 Answers

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!
like image 53
robkuz Avatar answered Jul 11 '26 21:07

robkuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!