How to have multiple objects extend 1 object in javascript?

149 views Asked by At

In javascript, I have a object (like an abstract class) defined like

var abstractclass = function() {

};

Now I want to have some other classes extend abstractclass. This is how I do it, but I don't think it's the best way. I just create an instance of the parent in the class, and then I just use the parent.

var abstractclassA = function() {
    var parent = new abstractclass();
};

var abstractclassB = function() {
    var parent = new abstractclass();
};

var abstractclassC = function() {
    var parent = new abstractclass();
};

var instance1 = new abstractclassA();
var instance2 = new abstractclassB();
var instance3 = new abstractclassC();

Is there a better way?

Thanks

2

There are 2 answers

1
Drago96 On

Usually I do this:

var abstractClass = function(){

};

var classB = function(){

};

classB.prototype = new abstractClass();

this way, the instance of classB will result as instance of abstractClass too

0
YakirNa On

If it is possible for you to use a library like underscorejs they have an extend function, I think it will do what you want. If not, then you can take a look at it's Annotated Source and see how they implemented it. Lastly, backbone's objects do something very similar to what you seek. So you can also take a look at their Annotated Source