2012-05-24 117 views
11
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。我如何扩展构造函数(追加?),以便我可以访问原始对象的属性?coffeescript扩展类的构造函数

回答

16

您需要明确地调用super才能使其工作。调用superWideRedGuy将调用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' 
+3

OMG,我一直在努力去理解'super',现在我完全理解了。非常感谢! – Fresheyeball

+0

@Fresheyeball乐于帮忙! – benekastah