How to extend javascript classes

The intrinsec objects of javascript (String, Number, Date, etc) are missing a lot of handy methods. God knows why. Example, you don’t have a trim() function on a String object. Maybe the developers thought that it was easy enough to write theString.replace(/^\s*|\s*$/g, “”) to trim a string but that’s not the kind of ugly code I want to see everywhere in my projects. It’s unesthetical. To do this, I have to use prototype.

So I want to add a trim() method to all my objects that are String class.

[source:javascript]

String.prototype.trim = function()
{
return this.replace(/^\s*|\s*$/g, “”);
}

[/source]

Easy.

Special note : I don’t want you to copy/paste that code. It’s for the purpose of the demonstration only.

I can do the same thing for every objects wheter they are intrinsic javascript classes, third-party classes or my own classes.

Commentaires

  1. skid November 15 2007 at 21:42:02

    Hi,

    Thanks for all your info.

    I tried to make something similar, but not with strings, with objects. I wanted a function to set the alpha for a DIV.

    It sounds like this:

    Object.prototype.setAlpha = function (alpha) {
    this.style.filter = ‘alpha(opacity: ‘ + alpha + ‘)’;
    this.style.MozOpacity = alpha / 100;
    this.style.KhtmlOpacity = alpha / 100;
    this.style.opacity = alpha / 100;
    }

    and I call it with: bgDiv.setAlpha(80);

    Works in FF but doesn’t in IE (6). :( Anyway, the content of the function is irrelevant, as the call of the function itself is the problem and gives the error in IE.

    Any ideas?

Post a comment

Comments are moderated and innapropriate ones won't be approved. Please respect this public space.