Differential inheritance in JavaScript

Introduction

Differential Inheritance is a common prototype-oriented model that uses the concept that most objects are derived from other, more generic objects, and only differ in a few small aspects. Each object maintains a reference to its prototype and a table of properties that are different.

Example

The following code provides a simple method for "cloning" an object:

Object.prototype.clone = 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 clone, 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 clone method and differential inheritance.

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

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

See also

Document Tags and Contributors

Tags:
Contributors to this page: Np, Bergi, dbruant
Last updated by: Bergi,