Where to add a prototype String

I am currently using JavaScript (CommonJS) in Titanium Studio and am wondering about prototyping. Suppose I want to add a new function to an existing class. For example:

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

What is the most suitable place where I have to add this code so that it becomes available for all classes at once?

Thanks in advance.

+7
source share
3 answers

Well, I found the best answer (Ivan Škugor), and I want to put it here to share with anyone who has the same question. Thank you for your help.

“Extending your own prototypes is not a good idea at all. In this particular case, this should not be a big problem in some other environments, but using CommonJs is a problem because every CommonJs module is a new JS context, which means a pure JS environment. So, everything that you do with the environment (for example, extending your own prototypes) will not be reflected in other modules. Because of this, it is best to write a "utils" module with auxiliary functions and "require" it anywhere. "

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

- Ivan Škugor

+8
source

Your example is useful because most browsers have their own cropping method, so it’s best to test for the native one before adding your own:

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

Just make sure it is defined before any code tries to use it and you are installed!

+4
source

All Articles