1. Computing & Technology

JavaScript By Example

Object Oriented: 21. Multiple Inheritance

From , former About.com Guide

As with many languages, JavaScript does not support multiple inheritance using the mechanism that it allows for single inheritance. You cannot just assign multiple values to the prototype in order to inherit from more than one object.

The simplest way to handle multiple inheritance in JavaScript is to expand the code that we use for providing actual copies of objects to allow for more than one object to be copied into the new object. To the deepCopy function we defined in an earlier example we add an additional function which we will call "multi" which takes any number of objects as parameters and will copy all of the properties and methods from those objects into our new object. After the function finishes running our new object will contain all of the properties and methods belonging to all of the objects passed to the multi function with any duplications in property or method names having the values assigned from the object specified in the earliest parameter (so any values that you want to be specific to this object should be specified first by creating an anonymous object containing those specific values as shown in this example with creating the 'a' and 'b' properties).

Note that combining objects together like this does not keep track of the actual inheritance within JavaScript itself. None of the usual tests you would perform to test if newobj inherits from either parent1 or parent2 would return true because the objects have been copied instead of using inheritance.


deepCopy = function(p,c) {
  var c = c||{};
  for (var i in p) {
    if ('object' === typeof p[i]) {
      c[i] = (p[i].constructor === Array)?[]:{};
      deepCopy(p[i],c[i]);
    } else c[i] = p[i];}
  return c;
};

multi = function() {
  var c = {};
  for (var i = arguments.length - 1; i >= 0; i--)
    deepCopy(arguments[i],c);
  return c;
);

newobj = multi({a: 1, b: 'hello'}, parent2, parent1);

©2012 About.com. All rights reserved.

A part of The New York Times Company.