2012-07-17 71 views
29

我有以下代码:调用coffescript超级方法

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 

为什么超级未定义?如何调用父级方法以扩展它?由于

+0

你猜是我的猜测......让我不知道他们为什么不只是使它像几乎所有人猜测它应该工作?也许是一个有趣的讨论 – PandaWood 2016-07-05 07:16:06

回答

63

,我发现自己的答案,它应该是:

class Dog extends Animal 

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

不要犹豫,把你的答案标记为正确。 – TheHippo 2012-07-17 17:43:11

+2

不应该是'super()'? – 2014-07-29 17:43:13

+2

@Ryan_IRL当你调用super时,你不需要使用'()'。编译器可以告诉你,当你使用'super'关键字时,你正在调用这个函数。 – grammar 2014-10-17 20:44:55