SYSK 336: Three Ways to Extend a Existing JavaScript Type

Since I haven’t seen a clear and a relatively concise explanation on this topic, I decided to create this blog post…

 

If you want to add a function (i.e. extend) to an existing type, there are three ways that I know of to accomplish this. For example, take the existing String object which comes with 28 functions (btw, the following applies to any object, not just ones defined in the language itself). However, the frequently desired ltrim and rtrim functions that remove a specified character are not in that list…

 

Method 1: You could add the ltrim function to the String type itself:

 

String.ltrim = function(text, removeChar)

{

    var result = text;

   

    for (i = 0; i < text.length; i++)

    {

        if (text.substr(i, 1) != removeChar)

        {

            result = text.substring(i, text.length);

            break;

        }

    }

   

    return (result);

}

Note that if you were to use this keyword, it would represent the String object, not the text you’re working with – that’s why you have to pass in the actual text. If you’re a C# developer, this probably reminds you of static functions (shared in VB.NET).

Here is an example of invoking the newly defined ltrim function:

var s1 = " Hello, World!";

alert('\'' + String.ltrim(s1, ' ') + '\'');

 

 

Method 2: You could add the ltrim function to the template used to create an instance of the String object, a.k.a. prototype:

 

String.prototype.ltrim = function(removeChar)

{

    var result = this;

   

    for (i = 0; i < this.length; i++)

    {

        if (this.substr(i, 1) != removeChar)

        {

            result = this.substring(i, this.length);

            break;

        }

    }

   

    return (result);

}

 

Note that this time, the ltrim function behaves just like any instance method in C# or VB.NET.

 

Here is an example of calling it:

 

var s1 = " Hello, World!";

alert('\'' + s1.ltrim(' ') + '\'');

 

Method 3: This method is not very useful for functions like ltrim but is very useful for instance properties:

 

var s1 = new String("Hello, World!");

s1.createdOn = new Date();

alert(s1.createdOn);

 

As expected, trying to execute the following code:

var s2 = new String("Another string");

alert(s2.createdOn);

 

will result in alert box showing ‘Undefined’.

 

 

Interestingly, constructing the string object implicitly will also result in an ‘Undefined’ alert:

 

var s1 = "Hello, World!";

s1.createdOn = new Date();

alert(s1.createdOn);