Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  4] [ 7]  / answers: 1 / hits: 16553  / 12 Years ago, wed, june 27, 2012, 12:00:00

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.


More From » titanium

 Answers
13

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


[#84623] Tuesday, June 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;