Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

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 "inherit" 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(){ 
    return this.firstName ?
               (this.lastName ?
                   this.firstName + " " +this.lastName :
                   this.firstName) :
               (this.lastName ?
                   this.lastName :
                   "a Person");
};
 
JoePerson = person.inherit();
JoePerson.firstName = "Joe";
alert( JoePerson.toString() );

See also

Document Tags and Contributors

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