JavaScript Array Prototype Property
This tutorial covers the prototype property for JavaScript arrays. The prototype property (not related to the well known JavaScript library) gives you access to the native JavaScript Array object's properties and methods.
While assigning properties and methods can be done quite simply on custom objects or single instantiated objects, using the prototype property is the only way to assign new properties and methods to the native Array object - for the life of your script (or its variables).
Using the Prototype Property with JavaScript Arrays
With the script below, we give all JavaScript arrays (for the life of the script) a new method, thanks to the prototype property:
// Create a new function for arrays
function displayArrayLength() {
alert( this.length );
}
// Give Array objects a new method
Array.prototype.showSize = displayArrayLength;
var arlene = new Array("I","learn","JavaScript");
arlene.showSize();
On purpose, we gave a different name to the function and the new method: they could have shared the same name, but do not have to. The last line of our script uses our new method to display the array's size:
The prototype property can be used not only on Array objects, but any other JavaScript native and custom objects.
Test the Array Prototype Property
Interactively test the array prototype property by editing the JavaScript code below and clicking the Test Array Prototype Property button.
Browser support for JavaScript array prototype property | |||
---|---|---|---|