Enhancing Javascript’s built in types

Share this article

Javascript is often falsely derided as a simple language, devoid of the object oriented features so favoured by other modern scripting languages. People holding this opinion really need to take another look at the language, for beneath its beginner friendly interior Javascript packs some powerful language features. In addition to its support for functional programming (where functions can be passed around a script in the same way as the data structures they operate on) Javascript supports a form of OOP known as prototype-based inheritance.

The web is already awash with tutorials on object oriented Javascript, so rather than rehashing them I’m just going to demonstrate one of the neater things you can do with prototype inheritance: add new capabilities to Javascript’s built in types. The following is one of my favourite examples:

Array.prototype.indexOf = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[ i] == value) {
return i;
}
}
return -1;
}

The above code adds a brand new method to the Javascript Array type called indexOf, which takes a value and returns the first index of the array containing that value, or -1 if the value isn’t found in the array. By assigning a new property to the prototype of the Array class, the new property (which in this case is a function) is made available to all other array objects, even those that have already been created.

Another class that’s ripe for enhancement is the String class. Here’s a simple trim() function which returns a copy of the string with any leading and trailing whitespace removed:

String.prototype.trim = function() {
var match = /s*(.*?)s*/.exec(this);
return match[1];
}

There’s a thread on the SitePoint forums discussing this technique in more detail. Thanks go to Octal for suggesting this as a topic for a blog entry.

Simon WillisonSimon Willison
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form