【问题标题】:coffeescript extend class constructor咖啡脚本扩展类构造函数
【发布时间】:2012-06-01 21:32:39
【问题描述】:
 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。如何扩展构造函数(追加?)以便可以访问原始对象的属性?

【问题讨论】:

    标签: oop coffeescript


    【解决方案1】:

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

    【讨论】:

    • 天啊,我一直在努力理解super,现在我完全理解了。非常感谢!
    猜你喜欢
    • 2013-10-30
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2013-01-09
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多