How to add useful utility methods to JavaScript

If you find in your day to day JavaScript work that a particular method or function is missing from the core language you can always just add it in yourself by taking advantage of the prototypal nature of the JavaScript language and modifying an object’s hidden prototype property.

Every object has a prototype property which links to an empty object. By adding methods to this hidden object you can augment the original Function.

// Augment the Function.prototype with a new method cleverly called 'method'
Function.prototype.method = function (name, func)
{
	// First lets check that the method we are trying to add doesn't already exist 
	// (just in case there is a conflict with another JS library)
	if (!this.prototype[name]) {
		// Create an Object method using 'name' as the property name and 'func' as the method content
		this.prototype[name] = func;
	}
}
 
// We can now use this new 'method' to add a 'trim' method to the String object...
String.method('trim', function()
{
	// We'll use a Regular Expression to trim the provided string 
	// (remove white space from either side of the String)
	return this.replace(/^\s+|\s+$/g, '');
});

We can now run a test to see if it works…

// Create a normal string (making sure there is a space either side 
// so we can test how effective our 'trim' method is) and display it's value
var myString = " this is my string ";
console.log( '/' + myString + '/' );
 
// Now create a new variable that will hold a updated version of myString 
// which has had its white space trimmed
var trimmed = myString.trim();
 
// Display the updated value so we can see the white space has been trimmed successfully.
console.log('/' + trimmed + '/');

This was just a very basic example but hopefully you’ll find it useful for adding missing features to the core JavaScript language. In fact the Prototype framework is based on this principle of augmenting existing objects and adding useful methods.

So unlike a framework such as jQuery which requires you to change the way you actually write JavaScript (by abstracting a lot of the known JavaScript methods through their own API) the Prototype JavaScript framework allows you to continue writing JavaScript in the same way but also benefit from the extra functionality.

Sep 13, 2009JavaScript - -
This site is mainly a place for me to share programming snippets which hopefully others will find useful. But otherwise you‘ll find me musing over Integral Theory (aka. the AQAL framework), MMA/UFC and my own kickboxing progress.
CommentsRSS0

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.