Writing jquery static util methods
I understand the concept of extending the jquery.fn to place your custom functions on the prototype chain of a jquery object, but in my case some of my utils don't need to be attached to a selector. I'm basically looking for a static method. So I wanted to know of any pitfalls of writing static methods directly on the jquery object as util methods.
Example:
jquery.myMethod = function(arg){
......
}
$.myMethod("blabl开发者_如何学运维a");
Thanks
As you seem to realize, it is a good idea to not dump all your utility functions into the global namespace. The less you can impact the global namespace, the better. If you already have jQuery, then your choices for where to put them are:
- As new methods on the jQuery object as:
jQuery.myUtil1()
,jQuery.myUtil2()
. - As new methods under one object on the jQuery object as:
jQuery.jfUtils.myUtil1()
,jQuery.jfUtils.myUtil2()
. - As new methods on one new global object (nothing to do with jQuery) as:
jfUtils.myUtil1()
,jfUtils.myUtil2()
.
Option 2) seems better to me than option 1) because you lessen the chance of colliding with other jQuery functions though you do add an extra lookup for each function call.
Option 3) seems perfectly acceptable to me as it only adds one new item to the global namespace so as long as you make the name reasonably unique, you should be OK.
So, I'd think you could go with either option 2) or option 3). Option 2) might be a little safer because you know the general extent of what is in that namespace, but either can work.
You shouldn't add static methods to jQuery. You don't gain anything by trying to. The point of extending jQuery is so that jQuery objects found with query strings will have methods on them. You're simply creating a global function, so just create a new top-level object to hold your functions.
精彩评论