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.
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.”
— Ivan Škugor