Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i modify the prototype of String?

I was about to create a trim function in javascript, but as i don't want to reinvent the wheel i googled for this method.
I found this link http://www.somacon.com/p355.php

The Solution it provided is:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

also it says if you don'y wnt to change the prototype of String then use this:

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
    return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/,"");
}

I would like to know in what scenario one should not modify the prototype of String or say any object.

like image 521
Rakesh Juyal Avatar asked Nov 09 '09 11:11

Rakesh Juyal


1 Answers

The trim functions are to be standardised in ECMAScript Fifth Edition, as well as already being present in some browsers. So:

  1. Yes, adding them to the prototype is totally appropriate, but

  2. You shouldn't add them to the prototype if they're already there, as you'll just be replacing a fast native-code function with a slow JavaScript one.

It is also typically marginally faster to do trim as two replaces:

// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}
like image 193
bobince Avatar answered Oct 12 '22 22:10

bobince