Startec
Startec

Reputation: 13206

How does Object.create not allow multiple inheritance in Javascript?

The MDN gives this explanation of inheritance in Javascipt (with the comments showing the prototype chain):

var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); 
// undefined, because d doesn't inherit from Object.prototype

Here it looks to me like c is inheriting from multiple classes. How is this not multiple inheritance?

Upvotes: 3

Views: 104

Answers (2)

doldt
doldt

Reputation: 4506

Multiple inheritance is when the parents are on the same level in the hierarchy:

c ---> b ---> Object.prototype ---> null
 \---> a ---> Object.prototype ---> null

In this case, it's simple inheritance from a class b which inherits from an other class a:

c ---> b ---> a ---> Object.prototype ---> null

Addendum: While the effects might seem similar (attributes of b will be also "found" in c via lookup in the prototype chain), do note the difference that multiple inheritance would allow a and b to have entirely different inheritance chains (in fact, inheritance "trees"), which is clearly not the case in your example.

Upvotes: 8

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

Multiple inheritance means inheriting in parallel from two or more classes, i.e. having two or more direct ancestors. They form a tree.

In your case there's only one direct ancestor: b, and a is b's direct ancestor, but indirect of c. They form a linear chain.

Upvotes: 1

Related Questions