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.
Definition and Usage The prototype is a property available with all JavaScript objects. The prototype property allows you to add new properties and methods to strings.
Description. In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string.
prototype. padZero = function (this : string, length: number) { var s = this; while (s. length < length) { s = '0' + s; } return s; };
Just make sure it's defined before whatever code is going to try and use it, and you'll be set!
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
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+$/, '');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With