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

4

1 回答 1

17

您需要明确调用super它才能工作。调用将调用super的构造函数,之后将正确定义。如需更深入的解释,您应该查阅咖啡脚本关于此事的文档WideRedGuyRedGuy@nameElem

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'
于 2012-05-24T21:58:04.540 回答