javascript 在哪里添加字符串原型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11231827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where to add String prototype
提问by junior
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:
我目前在 Titanium Studio 中使用 JavaScript (CommonJS) 并且有一个关于原型设计的问题。假设我想向现有类添加一个新函数。例如:
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.
提前致谢。
回答by junior
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.
好的,我找到了最好的答案(由 Ivan ?kugor 提供),我想把它放在这里与有相同问题的人分享。谢谢你的帮助。
"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."
“通常扩展原生原型并不是一个好主意。在这种特殊情况下,这在其他一些环境中应该不是什么大问题,但是通过使用 CommonJs,这是一个问题,因为每个 CommonJs 模块都是新的 JS 上下文,这意味着, 干净的 JS 环境。因此,您对环境所做的任何事情(例如扩展本机原型)都不会反映在其他模块上。因此,最好的方法是编写带有辅助函数的“utils”模块,并在任何地方“要求”它需要它。”
//utils.js
exports.trim = function(str) {
return str.replace(/^\s+|\s+$/g,"");
};
— Ivan ?kugor
— 伊万·库戈尔
回答by kennebec
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:
你的例子很好用,因为大多数浏览器都有自己的trim方法,所以最好在添加自己的之前测试原生:
String.prototype.trim= String.prototype.trim || function(){
return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
回答by Sean Johnson
Just make sure it's defined before whatever code is going to try and use it, and you'll be set!
只需确保在尝试使用它的任何代码之前定义它,您就可以设置!