Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending, instead of overwriting, the prototype

In our current codebase, we are creating classes like this

my_class = function(){
  //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.

like image 810
js_inher Avatar asked Feb 26 '23 00:02

js_inher


2 Answers

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.

like image 148
rsp Avatar answered Mar 07 '23 17:03

rsp


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
});
like image 24
Jacob Relkin Avatar answered Mar 07 '23 19:03

Jacob Relkin