是否可以在jQuery中创建名称空间? [英] Is it possible to create a namespace in jQuery?

查看:71
本文介绍了是否可以在jQuery中创建名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

YUI提供了一种在javascript中为您的方法等创建名称空间的好方法.

YUI has a nice way of creating a namespace for your methods etc. in javascript.

jQuery有什么相似之处吗?

Does jQuery have anything similiar?

推荐答案

lpfavreau 提供了扩展的解决方案带有您自己的方法的jQuery对象(以便其功能适用于实际的jQuery对象上下文).

lpfavreau offers the solution to extend the jQuery object with your own methods (so that their functionality applies on the actual jQuery object context).

如果您只想使用代码命名空间,则可以使用美元符号,如下所示:

If you're looking to just namespace your code you can use the dollar symbol like this:

$.myNamespace = { .. };

或"jQuery":

jQuery.myNamespace = { .. };

请谨慎选择您选择的名称空间,因为这会覆盖现有的jQuery方法(建议您首先在jQuery代码中进行搜索,以免出现这种情况).

Be careful with the namespace you choose as this can overwrite existing jQuery methods (I'd suggest to first search in the jQuery code so that you don't).

您可以点击以下链接:

You can follow this link: http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/

看看创建自己的函数来复制YUI的功能有多么容易:

See how easy it is to create your own function to replicate what YUI does:

// include jQuery first.
jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
    alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
    alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();

这篇关于是否可以在jQuery中创建名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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