Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to add String prototype

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.

like image 262
junior Avatar asked Jun 27 '12 17:06

junior


People also ask

What is string prototype?

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.

Can you append to a string in JavaScript?

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.

What property is used to extend the string prototype for all instances of string?

prototype. padZero = function (this : string, length: number) { var s = this; while (s. length < length) { s = '0' + s; } return s; };


3 Answers

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

like image 142
Sean Johnson Avatar answered Nov 15 '22 16:11

Sean Johnson


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

like image 30
junior Avatar answered Nov 15 '22 18:11

junior


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+$/, '');
}
like image 44
kennebec Avatar answered Nov 15 '22 18:11

kennebec