为什么他们在 JavaScript 中使用命名空间?
我看到他们在使用 indexeddb 的一些示例中使用名称空间: http://www.html5rocks .com/en/tutorials/indexeddb/todo/ 或 http://greenido.wordpress.com/ 2011/06/24/how-to-use-indexdb-code-and-example/
这样做有什么真正的好处吗?仅仅是为了组织相关的对象吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简而言之(据我所知),为了防止名称冲突和污染父名称空间。
Simply (AFAIK), to prevent name collisions and polluting parent namespaces.
德米安的回答一针见血:你对事物进行命名,以避免名称冲突和范围污染。
但它们也可以使您的代码更易于理解。举个例子,如果您有两个函数来显示和隐藏图像,它们可以称为
show
和hide
并存在于任何范围内。但您还必须在某处显示和隐藏 div,因此showImage
和hideImage
会更好。但随后您添加了淡入淡出、替换和缩放图像的方法,很快您就拥有了许多…Image
函数。将所有这些放入名为Image
的命名空间中,它们可以简单地是Image.hide
、Image.show
、Image.zoom等等。代码变得不言自明,您不必记住在编写代码时调用每个函数
...Image
,因为您可以说var Image = {show:..., hide: ..., ...etc}
或类似的。从结构上讲,您还可以通过将相关函数放在一起来获得更好的代码(正如您所提到的)。我喜欢使用的类比是,您的计算机桌面就像全局名称空间。您可以继续将文件放在桌面上,但它很快就会变得混乱,并且所有文件都需要非常复杂的名称才能保持唯一。因此,您可以使用文件夹来组织所有内容。每个人都看到使用文件夹来组织计算机上的内容的好处,那么为什么在编码时不使用类似的概念呢?
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
andhide
and exist in any scope. But you also have to show and hide a div somewhere, soshowImage
andhideImage
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 calledImage
and they could simply beImage.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 sayvar 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.