3

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!

1
  • I agree that this seems to be a bug in coffeescript. Have you created an issue for it? Commented Jul 5, 2014 at 18:51

1 Answer 1

5

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!
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I tried that but it seems like it copies the functions to B, defeating the purpose of the prototype chain. Am I mistaken?
I must admit I never have looked into the generated __extends function but it seems to me that it does create the correct prototype chain.
@tau It does that even if you don't call super. What is your point? All the chains are there: b = new B() A::hello = -> "Hello" alert b.hello()
If I inspect the objects in Chrome, both the sub and superclass have their own hide methods. Is that what it should say? I would expect the hide method to show up only in the superclasses __proto__ property, but I might be misunderstanding Chrome. I thought the functions should only exist in the superclass and not show up under the subclass. Here's an example:
class A constructor: -> test: => alert 'lol' class B extends A constructor: -> b = new B() b.test() console.log b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.