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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/527089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:16:32  来源:igfitidea点击:

Is it possible to create a namespace in jQuery?

jquery

提问by

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

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

Does jQuery have anything similiar?

jQuery 有什么类似的吗?

回答by Luca Matteis

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

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

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

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

$.myNamespace = { .. };

or the "jQuery":

或“jQuery”:

jQuery.myNamespace = { .. };

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).

请注意您选择的命名空间,因为这可能会覆盖现有的 jQuery 方法(我建议先在 jQuery 代码中搜索,这样您就不会这样做)。

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

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

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

看看创建自己的函数来复制 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();

回答by Wilk

This is how I create namespaces for my plugins:

这是我为插件创建命名空间的方式:

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

And then:

进而:

$.MyNamespace.MyPlugin ();

回答by lpfavreau

jQuery has a bunch of plugins that extend the base functionality. There is this pluginfor easy namespaces.

jQuery 有一堆插件可以扩展基本功能。有这个插件用于简单的命名空间。

回答by Tsvetan Kintisheff

The namespaceplugin is COMPLETELY UNNECESSARY!The oldest trick in the world, the use of arguments.callee, Function.prototype and then calling a new Function instance, allows you to create nested namespaces with $.fn.extend!

命名空间插件是完全没有必要的!世界上最古老的技巧,使用arguments.callee、Function.prototype 然后调用一个新的Function 实例,允许您使用$.fn.extend 创建嵌套命名空间!

Here is a plain and simple example:

这是一个简单明了的例子:

    ;(function($){
    var options= {
        root: function(){ //you don't have to call it 'root', of course :)
            //identify the function from within itself with arguments.callee
            var fn= arguments.callee;

            //'this' at this level is the jquery object list matching your given selector
            //we equate fn.prototype to this 
            //thus when we call a new instance of root, we are returned 'this'
            fn.prototype= this;

            fn.value= function(){
                //Note: "new this" will work in the below line of code as well,
                //because in the current context, 'this' is fn;
                //I use fn to make the code more intuitive to understand;
                var context= new fn; 

                console.log(context, fn.prototype); //test
                return context.html(); //test
            }

            return this;
        }
    }

    //you can obviously append additional nested properties in this manner as well
    options.root.position= function(){
        var context= new this; //in this context, fn is undefined, so we leverage 'this'

        console.log(context, this.prototype); //test
        return context.offset(); //test
    }

    //don't forget to extend in the end :)
    $.fn.extend(options);

})(jQuery);

;$(function(){
    var div= $('div#div')
        .root();

    console.log(div.root.value());
    console.log(div.root.position());
});

回答by eithed

If you want to use jQuery in this manner:

如果您想以这种方式使用 jQuery:

$("*").namespace.do();

then currently there're no plugins doing that. (I can't find neither John Resig's jquery.space plugin which apparently stopped working in jQuery 1.4, nor Gilberto Saraiva plugin that apparently didn't work as expected). I would gladly take a look at John's function to see why it stopped working, and what can be done to make it work and quite frankly, it would be the best approach of creating uncluttered namespaces.

那么目前没有插件可以做到这一点。(我找不到明显在 jQuery 1.4 中停止工作的 John Resig 的 jquery.space 插件,也找不到显然没有按预期工作的 Gilberto Saraiva 插件)。我很乐意看看 John 的函数,看看它为什么停止工作,以及可以做些什么来使它工作,坦率地说,这将是创建整洁命名空间的最佳方法。

As per http://malnotna.wordpress.com/2009/01/12/jquery-namespace-support/another approach is to do namespacing as (using jQuery.Modularize by Ariel Flesler):

根据http://malnotna.wordpress.com/2009/01/12/jquery-namespace-support/另一种方法是进行命名空间(使用 Ariel Flesler 的 jQuery.Modularize):

$("*").namespace().do()

but such syntax isn't "pretty". We're also passing results from one function to another.

但这样的语法并不“漂亮”。我们还将结果从一个函数传递到另一个函数。

My approach to creating namespaces is not putting namespaces in the end, but at the beginning of $, so our $('*').namespace syntax becomes:

我创建命名空间的方法不是将命名空间放在最后,而是放在 $ 的开头,所以我们的 $('*').namespace 语法变为:

$.namespace("*").do()

Weirdly, I don't know why such approach isn't mentioned, as it easily allows you to create unclattered namespaces without overwriting already existing functions (by using $.sub()). Also, making it work doesn't require anything. So:

奇怪的是,我不知道为什么没有提到这种方法,因为它可以轻松地让您在不覆盖现有函数的情况下创建整洁的命名空间(通过使用 $.sub())。此外,让它工作不需要任何东西。所以:

(function($){
    $.namespace = $.sub();
    $.fn.test = function(){ return 1 };              
    $.namespace.fn.test = function() { return 2};
})(jQuery);

console.log($('*').test(), $.namespace('*').test());

And you're ready to go.

你准备好了。

回答by nologo

check out this blog: http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/

看看这个博客:http: //javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/

the self-invoking dynamic namespacing is what i've used before:

自调用动态命名空间是我以前使用过的:

var myApp = {};
(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;
    } 
})(myApp); 

window.console && console.log(
    myApp.next(),
    myApp.next(),
    myApp.reset(),
    myApp.next()
); //0, 1, undefined, 0

回答by rmurphey

Depending on what you're trying to do, jQuery's plugin architecture may be what you're looking for:

根据您尝试执行的操作,jQuery 的插件架构可能就是您正在寻找的:

$.fn.myPlugin = function() {
  return $(this).each(function() {
    // do stuff
  });
};

or ...

或者 ...

$.fn.myPlugin = function() {
  var myNamespace = {
    // your stuff
  };
};

really it depends on what you're trying to do.

这真的取决于你想要做什么。

http://docs.jquery.com/Plugins/Authoring

http://docs.jquery.com/Plugins/Authoring

回答by Ben Flynn

All credit to @Diego Fluery, I just took his slide deck and made a runnable code prototype, but it might save you a few minutes if you go this route:

感谢@Diego Fluery,我只是拿了他的幻灯片并制作了一个可运行的代码原型,但如果你走这条路,它可能会为你节省几分钟:

<!DOCTYPE html>
<html>
<head>
<script type="application/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="application/javascript">

    $(document).ready(function() {
        (function () {
            $.fn.AppRedirect = function() {
                this.sendRequest = parts.sendRequest;
                this.doRedirect = parts.doRedirect;

                return this;
            }

            var parts = {

                doRedirect: function() {
                    console.log('doRedirect');
                },

                sendRequest: function() {
                    console.log('sendRequest');
                }

            };
        })();

        $("body").AppRedirect().sendRequest();
        $("body").AppRedirect().doRedirect();
    });     

</script>
</head>
<body>
</body>
</html>