2011-02-24 115 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