2010-08-25 58 views
3

我似乎不能夠正確地覆蓋類的方法,使用下面的代碼...Javascript繼承問題

function core() { 
    console.log("CORE CONSTRUCTOR CALLED"); 
} 

core.prototype.output = function() { 
    return 'CORE'; 
} 

function sub1() { 
    console.log("SUB 1 CONSTRUCTOR CALLED"); 
    this.core(); 
} 

sub1.prototype = core.prototype; 
sub1.prototype.constructor = sub1; 
sub1.prototype.core = core; 

sub1.prototype.output = function() { 
    return 'SUB 1'; 
} 

function sub2() { 
    console.log("SUB 2 CONSTRUCTOR CALLED"); 
    this.core(); 
} 

sub2.prototype = core.prototype; 
sub2.prototype.constructor = sub2; 
sub2.prototype.core = core; 

sub2.prototype.output = function() { 
    return 'SUB 2'; 
} 

var oCore = new core(); 
var oSub1 = new sub1(); 
var oSub2 = new sub2(); 

console.log(oCore.output()); 
console.log(oSub1.output()); 
console.log(oSub2.output()); 

...我得到以下輸出...

CORE CONSTRUCTOR CALLED 
SUB 1 CONSTRUCTOR CALLED 
CORE CONSTRUCTOR CALLED 
SUB 2 CONSTRUCTOR CALLED 
CORE CONSTRUCTOR CALLED 
SUB 2 
SUB 2 
SUB 2 

我在做什麼錯?

回答

4

問題是...當你在發出行:

sub2.prototype = core.prototype; 

您使用的是相同的原型上sub2core,因此,當你調用.output()任何類中,功能core.prototype.outputsub2版本,因爲它是定義的最後一個版本。請記住,對象分配通過引用發生。

要複製你會看到常用的對象:

sub2.prototype = new core(); 
sub2.prototype.core = core; 

或者 - 如果你想避免調用構造函數,你可以使用jQuery的$.extend(sub1.prototype, core.prototype);複製的核心原型。如果你沒有jQuery,這是大致相同的:

sub2.prototype = {}; 
for (var method in core.prototype) sub2.prototype[method] = core.prototype[method]; 
sub2.prototype.constructor = core; 
sub2.prototype.core = core; 
+0

不使用JQuery(有意避免將代碼綁定到JS框架),但底部的例子完美地工作。謝謝。 – michael 2010-08-25 11:10:34