Sunday, 22 May 2011

Adding a method to a built-in JavaScript object

I discovered I can easily add my own methods to the String object - or any other built in object. JavaScript is missing a String.startsWith(prefix) method, so let's create one:


String.prototype.startsWith = function (s) {
    return this.length >= s.length  && this.substring(0, s.length) === s;
};

Now I can write
if (myString.startsWith("foobar)) {
    ...
}

or

if ("Saturday".startsWith("Sat")) {
   ...
}

So easy...but there is a problem. If I'm using a third-party JavaScript library, it might add an identically-named method to String, overriding my version. Their version will have different bugs than my version, leading to horribly difficult debugging sessions.

I don't yet know a sane solution to this. The best I've come up with is to give my own extra methods a nasty prefix.




No comments:

Post a Comment