是否可以在jQuery中创建命名空间?

52 jquery

YUI有一种很好的方法可以在javascript中为你的方法等创建命名空间.

jQuery有类似的东西吗?

Luc*_*eis 39

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

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

$.myNamespace = { .. };
Run Code Online (Sandbox Code Playgroud)

或者"jQuery":

jQuery.myNamespace = { .. };
Run Code Online (Sandbox Code Playgroud)

小心你选择的命名空间,因为这可以覆盖现有的jQuery方法(我建议先在jQuery代码中搜索,这样你就不会).

您可以点击此链接:http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/

看看创建自己的函数来复制YUI的作用是多么容易:

// 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();
Run Code Online (Sandbox Code Playgroud)


Wil*_*ilk 10

这就是我为插件创建名称空间的方法:

(function ($) {
    // do not overwrite the namespace, if it already exists
    $.MyNamespace = $.MyNamespace || {};
    $.MyNamespace.MyPlugin = function () {/*here's the logic*/}
})($);
Run Code Online (Sandbox Code Playgroud)

然后:

$.MyNamespace.MyPlugin ();
Run Code Online (Sandbox Code Playgroud)


lpf*_*eau 5

jQuery有许多扩展基本功能的插件。有一个用于简单名称空间的插件