6

Possible Duplicate:
Javascript multiple inheritance

Is there a way in JavaScript to do this:

Foo = function() {

};

Bar = function() {

};

Baz = function() {
    Foo.call(this);
    Bar.call(this);
};

Baz.prototype = Object.create(Foo.prototype, Bar.prototype);

var b = new Baz();
console.log(b);
console.log(b instanceof Foo);
console.log(b instanceof Bar);
console.log(b instanceof Baz);

So that Baz is both an instance of Foo and Bar?

Community
  • 1
  • 1
Petah
  • 45,477
  • 28
  • 157
  • 213
  • This was discussed on this question: http://stackoverflow.com/questions/7373644/javascript-multiple-inheritance – Ismael Ghalimi Jan 29 '13 at 01:50
  • @IsmaelGhalimi so it was. I did read that question, and only its accepted answer. While there is an answer in there, I would not call this a duplicate. – Petah Jan 29 '13 at 01:58
  • Let me read it again and the answers to your question. I might have missed something. Sorry if I did. – Ismael Ghalimi Jan 29 '13 at 02:06
  • The supplementary answer to another question is correct for this question. That how ever does not mean this question is a duplicate of that question. – Petah Jan 29 '13 at 02:10

1 Answers1

8

JavaScript does not have multiple inheritance. instanceof tests the chain of prototypes, which is linear. You can have mixins, though, which is basically what you're doing with Foo.call(this); Bar.call(this). But it is not inheritance; in Object.create, the second parameter only gives properties to copy, and is not a parent.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • If `instanceof` won't work, is there another way to test whether an object inherits from two different classes? – streetlight Apr 10 '14 at 19:10
  • 3
    @streetlight: No. In JavaScript I think testing for capabilities makes more sense than testing for parentage. That is, say you inherit from `Dog`; instead of `if (x instanceof Dog) x.bark()`, you'd write `if (x.bark) x.bark();` (or safer but more verbose, `if (typeof(x.bark) == "function") x.bark()`). – Amadan Apr 11 '14 at 04:24