在哪里添加字符串原型 [英] Where to add String prototype

查看:33
本文介绍了在哪里添加字符串原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 Titanium Studio 中使用 JavaScript (CommonJS) 并且有一个关于原型设计的问题.假设我想向现有类添加一个新函数.例如:

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?

提前致谢.

推荐答案

好的,我找到了最佳答案(由 Ivan Škugor 提供),我想把它放在这里与有相同问题的人分享.谢谢你的帮助.

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.

扩展原生原型一般不是一个好主意.在这种特殊情况下,这在其他一些环境中应该不是什么大问题,但是通过使用 CommonJs,这是一个问题,因为每个 CommonJs 模块都是新的 JS 上下文,这意味着干净的 JS 环境.因此,您对环境所做的任何事情(例如扩展原生原型)都不会反映在其他模块上.因此,最好的方法是编写带有辅助函数的utils"模块,并在任何需要的地方要求"它."

"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,"");
};

——伊万·斯库戈尔

这篇关于在哪里添加字符串原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆