Is jQuery namespace a good practice?

Can someone please explain to me that if using a namespace is good coding practice. And why is this needed? If this was a good approach, why didn't jQuery enable it by default. To provide this functionality, there is a separate plugin.

I saw this post mentioning several ways to do this. Someone mentioned a memory leak in a message that is troubling.

Finally, what is the best way to organize jQuery libraries?

thanks,

+6
source share
3 answers

Notes:

  • Moving names is good practice because you are less likely to have conflicting names with other scripts. Thus, only your namespace should be unique, but multiple namespaces can have the same functions in them.
  • jQuery uses a namespace and you don't need a plugin. The jQuery object itself is a namespace. Any function inside jQuery is a name-distance in the jQuery object. This is true for any JavaScript object.

In response to Amir's comment:

YUI reaches the namespace 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 jQuery.fn (or $.fn if you use the $ namespace for jQuery ().

+20
source

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

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

+3
source

require.js is best practice because it does not require unnecessarily adding objects to the window object. This also does not mean that you need to worry about the loading order of previous javascript files.

0
source

Source: https://habr.com/ru/post/891740/


All Articles