spacer
Yehuda Shiran December 16, 1999
Extending Classes with Prototypes
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

One of the characteristics of an object-oriented programming language is its extendibility. In JavaScript, the prototype property allows you to easily extend both JavaScript's intrinsic object classes, as well as your own. Once you extend a class of objects, JavaScript-intrinsic or otherwise, all existing and future instances of the extended class will support the new properties and methods.

Let's extend the Array class of JavaScript-intrinsic objects. Suppose we want to add a method that checks for negative numbers. The method should return true if there are at least one negative numbers, and false if there are no negative numbers in the array. First, you need to write a simple function that implements this method. You refer to the parent Array object as you do for any constructor function, with the this keyword:

function isNegative() { 
  for (var i = 1; i < this.length; i++)
  {
     if (this[i] <0) return true;
  }
  return false;
}

You add the new method to the Array object with the prototype property:

Array.prototype.checkIfNegative = isNegative;

The following code segment shows how to use the new method:

var a = new Array(1, 2, 3, -4, 5, 6);
var b = a.checkIfNegative();

The variable b should be equal to true.

Let's take another example. Suppose we want to add a method that accepts an integer n as an argument and computes the nth power of the array's smallest element:

function array_powerOfMin(n) {
  var i, min = this[0];
  for (i = 1; i < this.length; i++)
  {
     if (this[i] < min) min = this[i];
  }
  return Math.pow(min, n);
}

You add the new method to the Array object with the prototype property:

Array.prototype.powerOfMin = array_powerOfMin;

The following code segment shows how to use the new method:

var a = new Array(1, 2, 3, -4, 5, 6);
var b = a.powerOfMin(3);

The variable b should be equal to -64.


People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger