coffeescript extend class constructor

coffeescript, oop

Solution

You need to explicitly call `super` for this to work. Calling `super` in `WideRedGuy` will call `RedGuy`'s constructor, after which `@nameElem` will be properly defined. For a more in-depth explanation, you should consult coffeescript's documentation on the matter.

class RedGuy
      constructor : (@name) ->
          @nameElem = $ @name
          @nameElem.css color : red

class WideRedGuy extends RedGuy
      constructor : ->
          ## This line should fix it
          super # This is a lot like calling `RedGuy.apply this, arguments`
          @nameElem.css width : 900

jeff = new WideRedGuy '#jeff'

Problem

``` class RedGuy constructor : (@name) -> @nameElem = $ @name @nameElem.css color : red class WideRedGuy extends RedGuy constructor : -> @nameElem.css width : 900 jeff = new WideRedGuy '#jeff' ``` I would like `#jeff` to be both red and wide, but I always get `this.name is undefined`. How can I extend the constructor (append?) so that I have access to the properties of the original object?

Original source