2012-07-17 72 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