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?

4
  • This was discussed on this question: stackoverflow.com/questions/7373644/… Commented Jan 29, 2013 at 1: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. Commented Jan 29, 2013 at 1:58
  • Let me read it again and the answers to your question. I might have missed something. Sorry if I did. Commented Jan 29, 2013 at 2: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. Commented Jan 29, 2013 at 2:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If instanceof won't work, is there another way to test whether an object inherits from two different classes?
@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()).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.