1. Computing & Technology

JavaScript By Example

Object Oriented: 24. Borrowing A Constructor

From , former About.com Guide

Yet another way to implement inheritance in JavaScript is to use apply or call to borrow the constructor function of the parent to define the child. By doing this we can substitute what "this" refers to in the constructor function so as to use the same constructor function for creating multiple objects.

In this example the Rectangle constructor borrows the Shape constructor function and so anything inside the Shape constructor function (in this example the assignment of an id) gets run as part of creating a Rectangle using the parameters passed to the Rectangle constructor function and with "this" in the Shape function referring to the object being created (in this example "rect"). Note that the prototype is not inherited in this sample code and so the toString method is not created for a Rectangle. You would need to add extra code to copy the prototype in order to inherit the prototype as well.


Shape = function(id) {
  this.id = id;
}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function()
  {return this.name;};
 
function Rectangle(id, width, height) {
  Shape.apply(this, arguments);
  this.prototype.name = 'Rectangle';
  this.width = width;
  this.height = height;
}
 
rect = new Rectangle('rect', 4, 5);

©2012 About.com. All rights reserved.

A part of The New York Times Company.