coffeescript扩展类构造函数

时间:2012-05-24 21:56:05

标签: oop coffeescript

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

 class WideRedGuy extends RedGuy
       constructor : ->
           @nameElem.css width : 900

 jeff = new WideRedGuy '#jeff'

我希望#jeff既红又宽,但我总是this.name is undefined。如何扩展构造函数(追加?)以便我可以访问原始对象的属性?

1 个答案:

答案 0 :(得分:17)

您需要明确调用super才能生效。在super中调用WideRedGuy会调用RedGuy的构造函数,然后@nameElem将被正确定义。有关更深入的解释,您应该就此问题咨询coffeescript's documentation

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'