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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With