Differential inheritance in JavaScript

Introduction

Differential Inheritance is a common inheritance model used by prototype-based programming languages such as JavaScript. It operates on the principle that most objects are derived from other, more general objects, and only differ in a few small aspects; while usually maintaining a list of pointers internally to other objects which the object differs from.

Example

The following code provides a simple method that "inherits" an object:

Object.prototype.inherit = function(){
  // Create a new object with this as its prototype
  var p = Object.create(this);

  /* actually not necessary:
  // Apply the constructor on the new object
  this.constructor.apply(p, arguments);
  */

  return p;
};

Using inherit, it becomes possible to simply derive more specific objects from a generic prototype. The following is a simple example of building up increasingly more specific objects using the inherit method and differential inheritance.

var root = {}; // Could be any object with any prototype object

var record = root.inherit();
record.toString = function(){ return "a Record"; };
 
var person = root.inherit();
person.firstName = false;
person.lastName = false;
person.toString = function(){
    if (this.firstName) {
        if (this.lastName) {
            return this.firstName + " " + this.lastName;
        } else {
            return this.firstName;
        }
    } else if (this.lastName) {
        return this.lastName;
    } else {
        return "a Person";
    }
};
 
JoePerson = person.inherit();
JoePerson.firstName = "Joe";
alert( JoePerson.toString() );

See also