2012-02-04 28 views
1

我決定嘗試JavaScript的天才約翰Resig的「簡單的JavaScript繼承」這個博客頁面上詳述:使用John Resig的「簡單的JavaScript繼承」我怎樣才能在方法中調用超級方法加上額外的代碼?

http://ejohn.org/blog/simple-javascript-inheritance/

我很好奇,人們可能會如何覆蓋使用代碼的方法調用父類方法。換句話說,假設我開始與類:

var Person = Class.extend({ 
    init: function (name, age) { 
     this.name = name; 
     this.age = age; 
    } 
}); 

我延長該類來創建一個新的類工人

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
     this.name = name; 
     this.age = age; 
     this.occupation = occupation; 
    } 
}); 

有碼重複的方法的兩個版本init方法。下面兩行,不管我用哪一個類執行:

this.name = name; 
this.age = age; 

好像我應該能夠從英雄類的初始化中調用類的初始化方法方法,然後在職業屬性中加入額外的代碼行。儘管如此,我不能用Resig先生的代碼做到這一點。以下不工作:

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
     this._super(arguments); 
     this.occupation = occupation; 
    } 
}); 

只要從稱爲延長方法來創建工人類看到* this._super(參數)*它取代的全部工人初始化人的初始化留下我一個未定義職業財產。

有沒有人有任何建議如何解決這個問題,而不必修改先生Resig的代碼?我目前正在嘗試不同的方式來實現「超級」的概念,但是我無法使用現有代碼來處理這個事實的事實卡在我的腦海中。 :-)

更新:我意識到我在實施Resig先生的代碼時犯了一個小錯誤,這就是爲什麼我的描述如此。 @chuckj正確地指出Workerinit中的錯誤。

回答

5

更改工作者定義,

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
     this._super(name, age); 
     this.occupation = occupation; 
    } 
}); 

你不通過arguments陣列,可以調用_super與它預期的參數。

0

看來你的目標是代理argumentsthis._super。在這種情況下,您只需要apply()即可:

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
     this._super.apply(this, arguments); 
     this.occupation = occupation; 
    } 
}); 
相關問題