2011-02-24 122 views
4

在我們當前的代碼庫,我們正在創造這樣擴展,而不是覆蓋,原型

my_class = function(){ 
    //do some constructor stuff 
} 

my_class.prototype = { 
    var1 : 'value', 
    var2 : 'value', 
    var3 : 'value' 
    . 
    . 
    . 
    //etc 
} 

類有幾類這樣的,我想繼承一個超類。但是,如果我這樣做,我最終會覆蓋超類的原型。

my_super_class = function(){ 

} 

my_super_class.prototype.generic_function = function(){ 
    //all subclasses should have this function 
} 

my_subclass = function(){ 
    //constructory stuff 
} 

//inherit the superclass 
my_class.prototype = new my_super_class(); 

my_class.prototype = { 
    //oops, there goes my superclass prototype... 
    var1 : 'value', 
    var2 : 'value', 
    var3 : 'value' 
    . 
    . 
    . 
    //etc 
} 

有沒有比my_class.prototype.val1 ='value'更好的方法來做到這一點? ...繼承了超類之後?我想遵循我們當前代碼庫中的約定,因爲它很簡短並且重點突出。

回答

2

您可以編寫爲您處理財產分配的功能:

function extend(a, b) { 
    for(var prop in b) { 
     if(b.hasOwnProperty(prop)) { 
      a[prop] = b[prop]; 
     } 
    } 
} 

my_class.prototype = new my_super_class(); 

var my_class_proto = { 
    //... 
} 

extend(my_class.prototype, my_class_proto); 
3

你使用任何庫或框架?如果你這樣做,那麼你可以使用像Prototype的Object.extend或jQuery.extend這樣的東西。

您可能還會感興趣的是從ECMA-262 5th Edition開始的新的Object.create

3

你可以做的是寫一個merge功能:

function merge(one, other) { 
    for(var k in other) { 
    if(other.hasOwnProperty(k) && !one.hasOwnProperty(k)) { 
     one[k] = other[k]; 
    } 
    } 
} 

然後,你會跟這樣做的prototype

merge(my_class.prototype, { 
    var1 : 'value', 
    var2 : 'value', 
    var3 : 'value' 
    . 
    . 
    . 
    //etc 
}); 
+3

您不應該擴展Object.prototype。它可以打破其他代碼。 – 2011-02-24 01:01:25

+1

@Felix好了,修復。 – 2011-02-24 01:03:20

0

我也正在努力找到一個很好的語法這些東西在JavaScript中,但我見過這樣的事情:

// inherit the superclass 
myClass.prototype = new mySuperClass(); 

(function() { 
    this.var1 = 'value'; 
    this.var2 = 'value'; 
    // etc. 
}).call(myClass.prototype); 

Wh ich似乎總是寫着myClass.prototype