coffeescript扩展类构造函数

Fre*_*all 11 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'
Run Code Online (Sandbox Code Playgroud)

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

ben*_*tah 17

您需要显式调用super此方法.调用superWideRedGuy会调用RedGuy的构造,在此之后@nameElem将正确定义.有关更深入的解释,请参阅coffeescript关于此事的文档.

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'
Run Code Online (Sandbox Code Playgroud)

  • 天哪,我一直在努力理解"超级",现在我完全明白了.非常感谢! (3认同)