Quick Tip: How to Extend Built-in Objects in JavaScript

Quick Tip: How to Extend Built-in Objects in JavaScript

Constructor functions, like Array, offer a wide range of methods and properties that you can make use of. But have ever wished that one of these objects offered some method that isn’t built-in? Is there a way to do so yourself? Absolutely! Let’s see how.

Reversing a String

This little snippet takes advantage of the Array object’s “reverse” method, and applies its functionality to a given string. In effect, something like “hello” will be turned into “olleh,” and can be accessed by using “myString.reverse()”.

String.prototype.reverse = function() {
	return Array.prototype.reverse.apply(this.split('')).join('');
};

var myString = 'hello';
console.log(myString.reverse());

Bonus Question

Now that we have a basic of understanding of augmenting objects, can you figure out a way to write a custom “contains” method for the String object? For example, the jQuery library allows us to write things like:

$("div:contains('John')").css('fontWeight', 'bold');

The snippet above will search through all of the divs on the page, and then filter that wrapped set down to only those that contain the string “John.” How could we extend the String object, with raw JavaScript, to allow for this? Leave your solution in the comments, and we’ll discuss!



Leave a Reply

Your email address will not be published. Required fields are marked *