【问题标题】:basic inheritance with coffeescript, child override not called使用咖啡脚本的基本继承,未调用子覆盖
【发布时间】:2015-06-09 21:17:07
【问题描述】:

我遇到了意外的行为。我在我的子类中覆盖了一个函数,但仍在调用父类中的一个函数。我做错了什么?

class MyClassA
    myFnc: ->
        debugger
        @myFncTest()

    myFncTest: ->
        ## this one is called eventhough it's defined in extended class

class MyClassB extends MyClassA
    myFncTest: ->
        debugger


inst = new MyClassB()
inst.myFnc()

编辑

我正在使用 Marionette 模块,它包含在两个单独的文件 MyClassA 和 MyClassB 中

MyApp.module("MyModuleA", function(MyModule, MyApp, Backbone, Marionette, $, _)

class MyClassA
        myFnc: ->
            debugger
            @myFncTest()

        myFncTest: ->
            ## this one is called eventhough it's defined in extended class

MyApp.module("MyModuleB", function(MyModule, MyApp, Backbone, Marionette, $, _)

class MyClassB extends MyApp.MyModuleA.MyClassA

        myFncTest: ->
            debugger


    inst = new MyClassB()
    inst.myFnc()

【问题讨论】:

    标签: javascript coffeescript marionette


    【解决方案1】:

    如果我写以下内容:

    class MyClassA
        myFnc: ->
            console.log 'myFnc'
            @myFncTest()
    
        myFncTest: ->
            console.log 'hello from A'
            ## this one is called eventhough it's defined in extended class
    
    class MyClassB extends MyClassA
        myFncTest: ->
            console.log 'hello from B'
    
    
    inst = new MyClassB()
    inst.myFnc()
    

    然后运行

    ➜ coffee test.coffee
    myFnc
    hello from B
    

    我只收到“来自 B 的你好”。

    我猜你要么调用 super() ,要么它们是你代码中的其他副作用

    我用的是最新版的coffeescript:

    ➜ coffee -v
    CoffeeScript version 1.9.0
    

    【讨论】:

    • 感谢您的回答。我唯一的其他特定环境差异是我正在使用 Marionette 模块,请参阅编辑
    • 啊它有效!它只有在我将咖啡脚本升级到 1.9.1 时才开始工作。我以前在 1.8.0 上,但它不像上面描述的那样工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 2013-06-15
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多