Why do they use namespaces in javascript?
I saw that they use namespace in some example of using indexeddb: http://www.html5rocks.com/en/tutorials/indexeddb/todo/ or http://greenido.wordpress.com/2011/06/24/how-开发者_高级运维to-use-indexdb-code-and-example/
Are there any real benefit of doing so? Is it just for organize the related object?
Simply (AFAIK), to prevent name collisions and polluting parent namespaces.
Demian hit the nail on the head in his answer: You namespace things to avoid name collisions and scope pollution.
But they can also make your code easier to understand. Just as an example, if you have two functions to show and hide an image, they could be called show
and hide
and exist in any scope. But you also have to show and hide a div somewhere, so showImage
and hideImage
would be better. But then you add methods to fade, replace, and zoom the image, and soon you have lots of …Image
functions. Toss all those into a namespace called Image
and they could simply be Image.hide
, Image.show
, Image.zoom
and so on. The code gets self-explanatory, and you don't have to remember to call every function …Image
when you write it, since you can say var Image = {show:…, hide:…, …etc}
or similar. Structurally, you also get nicer code by keeping related functions together (as you mentioned).
The analogy I like to use, is that your computer's desktop is like the global namespace. You can keep putting files on the desktop, but it'll get messy really quickly, and all your files would need really complex names to be unique. So instead you use folders to organize everything. Everyone sees the benefit of using folders to organize stuff on their computer, so why not use a similar concept when coding?
Namespaces are usually used to avoid variable/function/method identifier collisions and keep the global namespace (if any) clear.
精彩评论