0

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

omega
  • 40,311
  • 81
  • 251
  • 474
  • possible duplicate of [How to inherit from a class in javascript?](http://stackoverflow.com/questions/2107556/how-to-inherit-from-a-class-in-javascript) – GKnight Jun 16 '15 at 19:07
  • Do you really mean "abstract" in the OOP sense? – Bergi Jun 16 '15 at 19:27
  • No, I just called it abstract. – omega Jun 16 '15 at 19:28
  • What are you doing with these `parent` variables? Nothing? Then what's that `abstractclass` thing all about? Please provide your whole, meaningful code. – Bergi Jun 16 '15 at 19:28

2 Answers2

0

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

YakirNa
  • 519
  • 1
  • 5
  • 15
-1

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

Drago96
  • 1,265
  • 10
  • 19
  • 1
    I would use Object.create instead (if you can cut support off at IE9). so classB.prototype = Object.create(abstractClass.prototype); or just pass in an object literal. – Danny Blue Jun 16 '15 at 19:22