调用coffescript超级方法(Calling coffescript super method

2019-06-26 08:05发布

我有以下代码:

    class Animal
        constructor: (@name) -> 
        say: () -> console.log "Hello from animal called #{ @name }"

    class Dog extends Animal

        say: () ->
            super.say()
            console.log "Hello from dog called #{ @name }"

    a = new Animal('Bobby')
    a.say()

    d = new Dog("Duffy")
    d.say()            

其结果是不

Hello from animal called Bobby
Hello from animal called Duffy
Hello from dog called Duffy

但我得到以下错误:

Hello from animal called Bobby
Hello from animal called Duffy
Uncaught TypeError: Cannot call method 'say' of undefined

为什么超级未定义? 如何调用父类的方法,以延长它? 谢谢

Answer 1:

我找到自己的答案,它应该是:

class Dog extends Animal

    say: () ->
        super
        console.log "Hello from dog called #{ @name }"


文章来源: Calling coffescript super methods