Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the performance repercussions of adding functions to the String class in JavaScript and Node.js?

What are the repercussions of adding functions to the String class in JavaScript? Is this a bad idea? E.g.,

// String functions
String.prototype.startsWith = function(string) {
    return (this.indexOf(string) === 0);
}
String.prototype.empty = function() {
    //console.log($.trim(this.valueOf()));
    if($.trim(this.valueOf()) == '') {
        return true;
    }
    else {
        return false;
    }
}
like image 455
Kirk Ouimet Avatar asked Jun 27 '11 17:06

Kirk Ouimet


1 Answers

Performance-wise, there is zero effect.

But it's still not a great idea, imo. You're now depending on globally altered state. What happens if some other module does the same thing? Or worse, does a slightly different thing, but using the same name? Ouch.

Better to just define functions that take String arguments, and then use the functions.

like image 65
isaacs Avatar answered Oct 19 '22 22:10

isaacs