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("blabla");
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:
jQuery.myUtil1()
, jQuery.myUtil2()
.jQuery.jfUtils.myUtil1()
, jQuery.jfUtils.myUtil2()
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With