Can the below example be considered Multiple Inheritance?
No
Can anyone please explain why?
Your AB
(which I will call C
from here on out) function doesn't actually extend A
nor does it extend B
:
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
A.call(this);
B.call(this);
}
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c is A', c instanceof A, 'c is B', c instanceof B);
You don't have any inheritance at all in that example. You do have function composition.
If you wanted to have inheritance, the C
function would need to have a prototype that points to an instance of either A
or B
:
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
A.call(this);
B.call(this);
}
C.prototype = new A();
//or
//C.prototype = new B();
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c is A', c instanceof A, 'c is B', c instanceof B);
Note that because the C
function has a single prototype you can only have single inheritance.
For object composition, it would be common to see a pattern along the lines of:
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
this.a = new A();
this.b = new B();
}
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c.a is A', c.a instanceof A, 'c.b is B', c.b instanceof B);