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

最佳答案

您需要显式调用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'

10-07 22:15