1. Technology
Send to a Friend via Email

JavaScript By Example

Object Oriented: 23. Parasitic Inheritance


Because JavaScript doesn't have the distinction between classes and objects that other object oriented languages have, there are a number of alternative ways that you can use inheritance within JavaScript. Parasitic inheritance was first proposed as a way of handling inheritance in JavaScript by Douglas Crockford. With this methodology you create an object by using a function that copies another object, augments it with the additional properties and methods you want the new object to have and then returns the new object.

This example demonstrates parasitic inheritance by defining a function that will create a rectangle object inheriting from a Shape object. Note that because Rectangle is an ordinary function rather than an object constructor, we do not need to use 'new' when we call it. Calling it with 'new' will make no difference though because the function returns an object and so we can call the function just as if it were an object constructor while actually allowing the code for defining a Shape object to do most of the work.

Shape = {name: 'Shape'};
Shape.prototype.toString = function()
  {return this.name;};

function Rectangle(width, height) {
  var rect;
  P = function() {};
  P.prototype = Shape;
  rect = new P();
  rect.width = width;
  rect.height = height;
  return rect;

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Object Oriented
  7. JavaScript By Example - Object Oriented: Parasitic Inheritance

©2014 About.com. All rights reserved.