开发者

Extending, instead of overwriting, the prototype

In our current codebase, we are creating classes like this

my_class = functi开发者_Python百科on(){
  //do some constructor stuff
}

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

There are several classes like this that I would like to inherit a super class. However, if I do something like this, I end up overwriting the superclass' prototype.

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
}

Is there a better way to do this than do my_class.prototype.val1 = 'value'; ... etc after inheriting the superclass? I would like to follow the convention from our current codebase because it is short and to the point.


Do you use any library or framework? If you do then the chances are that you can use something like Prototype's Object.extend or jQuery.extend.

What you might also find interesting is the new Object.create from ECMA-262 5th Edition.


What you could do is write a merge function:

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

Then, you'd do this with the prototype:

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


You can write a function that handles the property assignment for you:

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);


I'm also struggling to find a nice syntax for those things in JavaScript, but I've seen something like this:

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

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

Which seems nicer than writing myClass.prototype all the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜