开发者

Is JQuery namespace a good practice?

开发者 https://www.devze.com 2023-03-16 06:55 出处:网络
Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn\'t include it by de开发者_StackOverflow中文版fault.

Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by de开发者_StackOverflow中文版fault. There is a separate plugin to allow this functionality.

I saw this post that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.

Lastly, what is the best way to organize JQuery libraries?

thanks,


Notes:

  • Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.
  • jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object. This is true for any JavaScript object.

In response to Amir's comment:

YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object. Their namespace function just builds it for you.

var lib = {
    util:{},
    widget:{},
    tool:{}
};

//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};

//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};

In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.


Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:

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


require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files.

0

精彩评论

暂无评论...
验证码 换一张
取 消