Why do they use namespaces in javascript?

你说的曾经没有我的故事 提交于 2019-12-11 11:13:11

问题


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?


回答1:


Simply (AFAIK), to prevent name collisions and polluting parent namespaces.




回答2:


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?




回答3:


Namespaces are usually used to avoid variable/function/method identifier collisions and keep the global namespace (if any) clear.



来源:https://stackoverflow.com/questions/7277130/why-do-they-use-namespaces-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!