Inheritance through Prototypes: How to Extend Classes with Prototypes - www.docjavascript.com
Extending Classes with Prototypes
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 n
th 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
.
Produced by Yehuda Shiran and Tomer Shiran
Created: January 18, 1999
Revised: January 21, 1999
URL: https://www.webreference.com/js/column34/class.html