Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coffeescript extend class constructor

 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?

like image 491
Fresheyeball Avatar asked May 24 '12 21:05

Fresheyeball


1 Answers

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'
like image 108
benekastah Avatar answered Oct 24 '22 05:10

benekastah