0

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?

Richard
  • 5,840
  • 36
  • 123
  • 208

1 Answers1

1

The problem is that you didn't put the doSomething method in Foo.prototype, you put it directly in each Foo object. You should define it as:

var Foo = function() {
    // Foo constuctor code here
};
Foo.prototype = {
    doSomething: function(input) {
        console.log("doSomething: ", input);
    }
}

You can even see this in the definition in the question you linked to, in its definition of myMethod.

Barmar
  • 741,623
  • 53
  • 500
  • 612