CoffeeScript扩展类构造函数

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未定义的错误。如何扩展构造函数(追加?),以便我可以访问原始对象的属性?

1个回答

17

你需要显式调用super才能使其正常工作。在WideRedGuy中调用super将会调用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'

3
哇,我之前一直很难理解super关键字,现在我完全明白了。非常感谢! - Fresheyeball

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接