【问题标题】:How to know when a Class is inherited with Coffeescript extends?如何知道一个类何时被 Coffeescript 继承?
【发布时间】:2013-02-03 10:01:53
【问题描述】:

我希望使用与 Ruby 提供的静态方法 'inherited' 相同的方法,正如您在其文档中看到的用于模块操作目的:

class Foo
  @inherited: (subclass) ->
    console.log('hey hou')

class Hey extends Foo

class Hou extends Foo

输出:

=> hey hou
=> hey hou

如何使用 Coffeescript 'extends' 实现这一点?我的意思是,如果我使用 Backbone.js 的“扩展”方法,我可以覆盖它。但 Coffeescript 会编译它,但这是不可能的。

有什么想法吗?

【问题讨论】:

    标签: javascript inheritance backbone.js module coffeescript


    【解决方案1】:

    亚历克斯·韦恩的回答是完全合法的,也是正确的做法。

    但是,如果您确实需要它(例如,出于调试目的)而无需进行显式函数调用,您也可以在每个文件的开头重新定义 CoffeeScript 编译器生成的 __extends 函数。由于__extends 是CoffeeScript 中的保留关键字,因此必须在纯JavaScript 中重新定义它并使用反引号嵌入到CoffeeScript 文件中:

    `
    __extends = (function (extend) {
        return function (child, parent) {
            // Do actual heritage
            var result = extend(child, parent);
            // Do something with child or parent
            if (parent.inherited instanceof Function) parent.inherited(child);
            // Return the result as in the original '__extends' function
            return result;
        }
    })(__extends);
    `
    

    【讨论】:

      【解决方案2】:

      没有。

      它曾经有这个,它被删除了。有些人想把它放回去,但它需要如何工作却很奇怪。

      来源中对此的一些参考:

      建议的解决方法依赖于子类的显式调用。

      class A extends B
      
        # child class calls extended hook of parent class explicitly.
        B.extended(this)
      
        classBody: ->
        methods: ->
        goHere: ->
      

      【讨论】:

        猜你喜欢
        • 2011-06-04
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-01
        • 2014-11-22
        相关资源
        最近更新 更多