[英]Do I have to avoid being invasive when building my own JavaScript library or jQuery plugin?
Lately, I've been building some JavaScript libraries as well as some jQuery plugins, and I have a 'utils.js' file where I put all my custom functions for Array
, String
, Number
, etc. and which I include in the final minified version of the library or plugin. 最近,我一直在构建一些JavaScript库以及一些jQuery插件,我有一个'utils.js'文件,我将所有自定义函数放入
Array
, String
, Number
等,并将其包含在final中缩小版本的库或插件。
Something like this: 像这样的东西:
String.prototype.custom_method = function() {
// Do custom stuff
};
Array.prototype.custom_method = function() {
// Do custom stuff
};
So, these are my questions: 所以,这些是我的问题:
Given jQuery and Modernizr do the exact same thing (provide a lot of out-of-the-box ability, while still the average person only utilizing 10%) I don't see an issue. 鉴于jQuery和Modernizr做同样的事情(提供了很多开箱即用的能力,而普通人只使用了10%)我没有看到问题。
Is it bloated? 它臃肿了吗? Perhaps.
也许。 It would be ideal to only include the files you use (one of the great things about Google's approach to plugins, include what you need), however I don't see any bigger threat than what already exists.
理想的做法是只包含您使用的文件(Google的插件方法,包括您需要的内容之一),但是我没有看到比已经存在的更大的威胁。
I think you compartmentalizing them is a step in the right direction for the sake of multiple libraries maybe needing them (no duplicate declarations). 我认为你划分它们是朝着正确的方向迈出的一步,因为多个库可能需要它们(没有重复的声明)。 But, if you're really worried about it, you could do a test-declare setup:
但是,如果你真的担心它,你可以做一个测试声明设置:
if (typeof foo === 'undefined'){
function foo(){}
}
But once again, it would need to be included in/on every library you release/build, instead of an "all-encompassing" library. 但是,再一次,它需要包含在您发布/构建的每个库中/上,而不是“无所不包”的库。
Here is a good discussion of what you're asking. 以下是对您要问的内容的一个很好的讨论。
http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/ http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/
Short answer: Extending native types is, not great, but ok. 简短回答:扩展原生类型并不是很好,但还可以。 Wrapping them like underscore.js does is better because there is no chance of future conflicts that way.
像underscore.js一样包装它们会更好,因为这样就不会有未来的冲突。
It depends on the audience. 这取决于观众。 You will never win over an enterprise audience if you add or overwrite methods to default classes.
如果向默认类添加或覆盖方法,则永远不会赢得企业受众。 Who knows what conflicts that could cause?
谁知道可能导致的冲突? Take a look at underscore.js http://documentcloud.github.com/underscore/ a library that strives not to do this with decorator methods.
看一下underscore.js http://documentcloud.github.com/underscore/一个不打算使用装饰器方法做到这一点的库。 This is much more friendly to users with codebases that may include, in addition to your code, goodness knows what.
这对于拥有代码库的用户来说更加友好,除了代码之外,代码可以包括善良知道什么。
However, if your code can assuredly be run by itself, in a silo, go for it. 但是,如果你的代码可以自己运行,那么在一个孤岛中,去吧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.