简体   繁体   中英

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.

Something like this:

String.prototype.custom_method = function() {
  // Do custom stuff
};

Array.prototype.custom_method = function() {
  // Do custom stuff
};

So, these are my questions:

  • Do I have to avoid this? Is this a bad practice?
  • Would it be better if I put these methods in a per library/plugin scope?

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.

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.

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/

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM