Where to add String prototype
Asked Answered
N

3

10

I'm currently using JavaScript (CommonJS) in Titanium Studio and have a question about prototyping. Suppose that I want to add a new function to an existing class. For instance:

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

What is the most appropriate place where I should add this code so It became available for all classes right away?

Thanks in advance.

Negotiate answered 27/6, 2012 at 17:26 Comment(0)
N
12

Ok, I found the best answer (by Ivan Škugor) and I want to put it here to share with who have the same question. Thanks for your help.

"Extending native prototypes in general is not good idea. In this particular case, that shouldn't be much of a problem in some other environments, but by using CommonJs, that is a problem because every CommonJs module is new JS context, which means, clean JS environment. So, anything you do with environment (like extending native prototypes) won't be reflected on other modules. Because of that, the best is to write "utils" module with helper functions and "require" it anywhere you need it."

//utils.js
exports.trim = function(str) {
    return str.replace(/^\s+|\s+$/g,"");
};

— Ivan Škugor

Negotiate answered 28/6, 2012 at 8:37 Comment(0)
N
5

Just make sure it's defined before whatever code is going to try and use it, and you'll be set!

Nicollenicolson answered 27/6, 2012 at 17:28 Comment(2)
Thanks for your answer Sean. But isn't there any convention on how/where should I do this?Negotiate
If you have a library that you use all over the place, you could always put it in there. I normally define functions that add on to built-in classes at the top of whatever library I'm including, to keep things neat and tidy. Much the same way as I define CSS attributes of HTML tags at the top of the CSS file, and classes/ids after.Nicollenicolson
G
5

Your example is a good one to use, because most browsers have their own trim method, so it is best to test for the native before adding your own:

String.prototype.trim= String.prototype.trim || function(){
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
Galenic answered 27/6, 2012 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.