Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript multiple inheritance and instanceof [duplicate]

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?

like image 875
Petah Avatar asked Jan 29 '13 01:01

Petah


1 Answers

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.

like image 197
Amadan Avatar answered Nov 18 '22 04:11

Amadan