2

I'm looking at methods of implementing multiple inheritance in JavaScript. I've done a lot of reading on the subject, and know there are several approaches, each with their strengths and weaknesses, but I haven't found a thorough analysis of Object.create(), at least not one in language that I can understand. I've done some experimenting and have come up with an approach that truly does achieve multiple inheritance using Object.create() (see the JSFiddle below).

https://jsfiddle.net/etymhecv/

In the above fiddle, the p variable is a Person, the e variable is an Employee (which inherits from Person) and ae is an AlienEmployee (which inherits from both the standalone class Alien, and from Employee (and hence Person)). The test Person.isPerson(ae) correctly detects that an AlienEmployee is a type of Person.

Can someone explain to me what disadvantages, if any, I may encounter by using the above approach?

2
  • Uncaught TypeError: Object.getOwnPropertyDescriptors is not a function. Weird. Commented Jun 3, 2016 at 0:42
  • @Marcus, it works for me in Chrome. Commented Jun 3, 2016 at 0:59

1 Answer 1

3

I have come up with an approach that truly does achieve multiple inheritance

Nope:

> var ae = AlienEmployee.create("Zeuss", "4321", "Marsodian")
| AlienEmployee.isAlienEmployee(p)
< true
> Alien.isAlien(p)
< false

Multiple prototypical inheritance is not possible in JavaScript, the prototype chain is always linear.

Your create methods do successfully employ a mixin pattern (either with Object.create/defineProperties(…, Object.getOwnPropertyDescriptors(…)) or with extend/Object.assign), but that's not really the dynamic inheritance we've known from Object.create.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, you're right! It's a shame that an object's prototype can't be an array of objects, rather than just a single object.
@user1420752: You've chosen the wrong language for that :-) I guess you could implement something like that with ES6 Proxies, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.