Get the latest news, exclusives, sport, celebrities, showbiz, politics, business and lifestyle from The VeryTime,Stay informed and read the latest news today from The VeryTime, the definitive source.

JavaScript By Example

27
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;
}

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.