Is it possible to create a namespace in jQuery?

后端 未结 8 954
星月不相逢
星月不相逢 2020-11-27 13:52

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

Does jQuery have anything similiar?

8条回答
  •  清歌不尽
    2020-11-27 14:00

    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 = { .. };
    

    or the "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).

    You can follow this link: 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:

    // include jQuery first.
    jQuery.namespace = function() {
        var a=arguments, o=null, i, j, d;
        for (i=0; i

提交回复
热议问题