-1

I have a question about inheritance in JavaScript. If I try to inherit Foo1 in Foo2 it does not matter in which order I do this. I can put Foo2's definition before Foo1 and it will still work correctly. Whereas if Foo3 is defined out of order the inheritance does not work.

function Foo1() {
  this.message = 'Hello World';
}

Foo1.prototype.displayMessage = function() {
  console.log(this.message);
}

function Foo3() {
  Foo2.call(this);
}

Foo3.prototype = Object.create(Foo2.prototype);

function Foo2() {
  Foo1.call(this);
}

Foo2.prototype = Object.create(Foo1.prototype);

var x = new Foo3();
x.displayMessage();

this example will give you a result saying that displayMessage is not a function of x. Which it should be. If I put Foo3 at the bottom and they are defined as Foo1 > Foo2 > Foo3 then all goes smoothly. So why does it work with only one inheritance Foo1 > Foo2 but it does not work correctly with 3? How can I deal with this issue?

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Issue is you are setting prototype of Foo3 and then adding Foo1 to Foo2's prototype. If you do in proper sequence, it works fine.

Following is a sample:

function Foo1() {
  this.message = 'Hello World';
}

Foo1.prototype.displayMessage = function() {
  console.log(this.message);
}

function Foo2() {
  Foo1.call(this);
}

Foo2.prototype = Object.create(Foo1.prototype);

function Foo3() {
  Foo2.call(this);
}

Foo3.prototype = Object.create(Foo2.prototype);

var x = new Foo3();
x.displayMessage();
Rajesh
  • 24,354
  • 5
  • 48
  • 79