user2251919
user2251919

Reputation: 675

How can I make an object inherit two objects in its prototype?

I am trying to make an object inherit from two other objects but doing it like so does not work, how can I make it work?

function a() {

};

a.prototype.iamA = function() {
alert("a");
};  

function b() {

};

b.prototype.iamB = function() {
alert("b");
};

function ab() {

};

ab.prototype = new a();
ab.prototype = new b();

console.log(new ab());

It seems that the prototype is overridden how can I add to it, I have also tried adding it to the prototype but this doesn't work either?

Upvotes: 3

Views: 153

Answers (1)

Hui Zheng
Hui Zheng

Reputation: 10222

Use object extension instead of assignment, e.g:

function extend(obj, source) {
    for (var prop in source) {
       obj[prop] = source[prop];
    }
    return obj;
}

then:

ab.prototype = extend(new a(), new b());         (1)

Or you may choose to use underscore's extend function.

ab.prototype = _.extend({}, new a(), new b());   (2)

Edit:

Strictly speaking, this is mixin instead of real multi-inheritance, since (new ab instanceof b) === false in both (1) and (2).

For more information, please take a look at this reference: No multiple Inheritance.

That said, mixin is probably enough for you. It turns out that people who think they need inheritance usually only need code reuse, not typing-related construction. This is especially true for the dynamic typing(or duck typing) language like JavaScript.

Upvotes: 8

Related Questions