编写jQuery静态util方法 [英] Writing jquery static util methods

查看:110
本文介绍了编写jQuery静态util方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解扩展jquery.fn的概念,以将您的自定义函数放置在jquery对象的原型链上,但就我而言,我的一些实用程序不需要附加到选择器上. 我基本上是在寻找一种静态方法.因此,我想知道将静态方法直接作为util方法写在jquery对象上的任何陷阱.

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.

示例:

jquery.myMethod = function(arg){
   ......
} 

$.myMethod("blabla");

谢谢

推荐答案

您似乎意识到,最好不要将所有实用程序函数都转储到全局名称空间中.您对全局名称空间的影响越少越好.如果您已经有了jQuery,则可以选择将它们放在何处:

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:

  1. 作为jQuery对象上的新方法,如:jQuery.myUtil1()jQuery.myUtil2().
  2. 作为jQuery对象上一个对象下的新方法,例如:jQuery.jfUtils.myUtil1()jQuery.jfUtils.myUtil2().
  3. 作为对一个新全局对象(与jQuery无关)的新方法,如:jfUtils.myUtil1()jfUtils.myUtil2().
  1. As new methods on the jQuery object as: jQuery.myUtil1(), jQuery.myUtil2().
  2. As new methods under one object on the jQuery object as: jQuery.jfUtils.myUtil1(), jQuery.jfUtils.myUtil2().
  3. As new methods on one new global object (nothing to do with jQuery) as: jfUtils.myUtil1(), jfUtils.myUtil2().

对我来说,选项2)比选项1)更好,因为尽管确实为每个函数调用添加了额外的查找,但是您减少了与其他jQuery函数冲突的机会.

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.

选项3)对我来说似乎是完全可以接受的,因为它只向全局名称空间添加了一个新项,因此只要您使名称合理唯一,就可以了.

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.

因此,我认为您可以选择选项2)或选项3).选项2)可能会更安全一些,因为您知道该名称空间中的内容的一般范围,但是任何一个都可以使用.

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.

这篇关于编写jQuery静态util方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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