Say I have two constructors:
A = function () {
this.x = 'x';
};
A.prototype.a = 'a';
B = function () {
this.y = 'y';
};
B.prototype.b = 'b';
How can I create an object ab that will inherit from the
prototypes of both of them? so the following example will work:
ab.a === 'a'; // true
ab.b === 'b'; // true
A.prototype.a = 'm';
ab.a === 'm'; // true
B.prototype.b = 'n';
ab.b === 'n'; // true
Thanks
You can’t, there’s only one prototype chain. You basically have three options:
Inherit from one, copy the other
All you can do in terms of having the properties on a single object is inherit from one of the prototypes and copy the properties of the other. Obviously that’s not quite what you want, because you don’t have the live reference aspect of the copied properties, but it’s all you can do in terms of having these properties on a single object.
Composition
Another option is composition:
So now,
abas anAaspect (call it an “A-ness”) in itsanessproperty, and aBaspect (call it a “B-ness”) in itsbnessproperty.Frequently when one thinks “I need multiple inheritance,” composition is a good alternative (even in systems that allow multiple inheritance). Not always, mind, but frequently.
If you need to add functions to the A-ness or B-ness of
abthat also have access to the other aspect, you can do that with closures. This can come up if, for instance, you have pass an object into a third-party library that expects to see anAinstance and call itsfoofunction, and we want to do something different infoobased on some state in ourBaspect. For example:Beware the above pattern, though, because it creates a new function for every instance generated by the
ABconstructor. If there are a lot, it could become a memory issue.At this point, we start straying into inheritance chains and supercalls, which I talk about in more detail in this blog post.
Link
BtoAIf you’re the designer of
AandB, it may make sense forBto inherit fromA, and then yourabcan be created by theBconstructor:…but that means that all
Bobjects are alsoAobjects, which may not be what you want.Off-topic: I haven’t added
vars to the above on the assumption there’s a reason they’re not there (e.g., they’re already declared in code you’re not showing).Off-topic 2: Unless you have a good reason, I always recommend using named functions rather than anonymous ones (the functions you’re assigning to
AandBare anonymous).