js_inher
js_inher

Reputation: 41

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.

Upvotes: 4

Views: 753

Answers (4)

Juliusz Gonera
Juliusz Gonera

Reputation: 4958

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.

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163258

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

Upvotes: 3

rsp
rsp

Reputation: 111356

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.

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816462

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

Upvotes: 2

Related Questions