JavaScript String Prototype Property
This tutorial introduces the prototype property for JavaScript strings. The prototype property (not related to the well known JavaScript library) gives you access to native JavaScript String objects' properties and methods.
While assigning properties and methods can be done quite easily on custom objects or single instantiated objects, using the prototype property is the only way to assign new properties and methods to the native String object - for the life of your script (or its variables).
Using the Prototype Property with JavaScript Strings
The script below assigns to all JavaScript strings (for the life of the script) a new method, by using the String prototype property:
// Create a new function for strings
function displayNumberOfChars() {
alert( this.length );
}
// Give String objects a new method
String.prototype.showLength = displayNumberOfChars;
var carter = new String("I learn JavaScript.");
carter.showLength();
We deliberately gave a different name to the function and the new method: they share the same name, but it is not a requirement. The last line of our script uses our new method to display the string's length:
The prototype property can be used not only on String objects, but any other JavaScript native, as well as custom objects.
Test the String Prototype Property
Interactively test the string prototype property by editing the JavaScript code below and clicking the Test String Prototype Property button.
Browser support for JavaScript string prototype property | |||
---|---|---|---|