I have this hierarchy:
public abstract class Foo {};
public class A extends Foo {};
public class B extends Foo {};
I want to model this hierarchy in javascript. So I've tried something like this:
var Foo = function () {
this.doSomething = function(input) {
//do something
}
};
var A = function() {
Foo.call(this);
this.AdoSomething = function(input) {
this.doSomething();
//do more things
}
}
var B = function() {
Foo.call(this);
this.BdoSomething = function(input) {
this.doSomething();
//do more things
}
}
And I setup the hierarchy like this:
var tempFoo;
if (type === 'A') {
A.prototype = Object.create(Foo.prototype);
tempFoo = new A();
tempFoo.AdoSomething(data);
} else {
B.prototype = Object.create(Foo.prototype);
tempFoo = new B();
tempFoo.BdoSomething(data);
}
This works just fine. But I'm wondering if there is a better way to do this. I would like the javascript objects to look like so:
var Foo = function () {
this.doSomething = function(input) {
//do something
}
};
var A = function() {
Foo.call(this);
this.doSomething = function(input) {
//call Foo's doSomething, super.doSomething()
//do more things
}
}
var B = function() {
Foo.call(this);
this.doSomething = function(input) {
//call Foo's doSomething, super.doSomething()
//do more things
}
}
But I can't use super
or class
because it's not supported in IE. I used this answer to try to call the parent method (Foo's dosomething) like so:
Foo.prototype.doSomething.call(this)
But this didn't work. I got an error saying cannot read property call of undefined.
What is the best way to setup the hierarchy in javascript?