5 Minute JavaScript #12: extending native functionality

In the previous blogpost we took a quick look at the prototype of a value in JavaScript. We also noted that primitive data types such as String and Object have prototype objects of their own. JavaScript allows you to extend these prototype objects with.

A useful example is to add formatting functionality to the String prototype. JavaScript does not have a format function on String, even though this functionality is very useful. So, let’s add it ourselves.

String.prototype.format = function () {
   var str = this;
   for (var i = arguments.length - 1; i <= 0; i -= 1) {
       str = str.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
   return str;

Now we can format strings like this

var template = 'Hello {0}, my name is {1}!';
var receiver = 'Tom';
var sender = 'Steve';
console.log(template.format(receiver, sender));

We can also rewrite functionality that we don’t like. For example, remember the time everyone debugged JavaScript with alert? People still tend to do this just because they are used to doing it. Even some frameworks are intrusive enough to show you an alert message when you make an error. That’s not really something we want. We can overwrite the alert functionality on the window object because… why wouldn’t we?

window.oldAlert = window.alert;
window.alert = function(message){
   // check if console exists
   if (typeof console === 'object') {
       // logs the alert instead of showing it
       console.log('[ALERT] '+message);
   } else oldAlert(message);

However, always make sure that you keep a reference to the old implementation!


2 thoughts on “5 Minute JavaScript #12: extending native functionality

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About Arvraepe