Apart from not cluttering the global namespace and gaining the ability to encaps开发者_StackOverflow中文版ulate code in private members, is there any benefit?
That really is the benefit. It allows you to use libraries without the risk of it overwriting your functions or you overwriting functions in them.
If it's all your code on the page (and you're absolutely positively sure that you'd never want to use any libraries ever) then the benefit isn't massive. However, it's still a good habit to cultivate.
A namespace is a useful concept because it provides a degree of isolation and protection from other JavaScript that might be running on your page. By defining a namespace and using it for variable definition we can avoid "overwriting" variables of the same name that we may not be aware of. Because we are using namespaced variable and function definitions, we need to put our script above the rest of the page markup so that the functions and objects we create and reference in the markup are available when the page loads.
Yes you're right. Apart from the benefits of namespaces, there are no benefits of namespaces.
But be sure to consider what would happen if you later do add more external scripts, or make your own scripts more complicated. Namespaces are quite light and easy to set up, and it's never harmful to be tidy from the start.
One more benefit I would like to add is that Namespace takes care of Memory leaks. Say for example you want to delete few 10 objects in you .js file after having used it. So instead of using "delete" keyword 10 times, you can wrap those 10 objects in a single object ( namespace ) and use the "delete" option once.
精彩评论