理解javascript全局命名空间和闭包
I'm trying to improve my understanding of the global namespace in javascript and I'm curious about a few things:
我正在努力提高我对javascript中全局命名空间的理解,我对以下几点感到好奇:
is there a "GOD" (i.e. a parent) object that all objects (since all things except primitives are objects) to answer to and if so would that object be "window" ?
有一个“GOD”(即父级)对象,所有对象(因为除了基元之外的所有东西都是对象)要回答,如果是,那么该对象是“窗口”吗?
why is it bad idea to have vars/functions on a global level?
为什么在全球范围内拥有变量/功能是个坏主意?
if it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this? example:
如果在全局范围内拥有vars /函数真的是一个坏主意那么闭包是避免这种情况的最佳方法吗?例:
function parent(){ var x = 'some value';//this var would be considered global to all children functions but not in the true global namespace function child1(){ x.someMethod() } function child2(){ x*something; } function child3(){ x+=something; child2() child1() } child3() } parent()
4 个解决方案
#1
24
-
Is there a god (i.e. a parent) object?
有神(即父母)对象吗?
Yes. More technically, it's the global object that all these primitives are members of; it just happens that in the browser, the
window
object is the global object.是。从技术上讲,它是所有这些原语都是其成员的全球对象;它恰好发生在浏览器中,窗口对象是全局对象。
> window.String === String; true
-
Why is it bad idea to have vars/functions on a global level?
为什么在全球范围内拥有变量/功能是不错的主意?
Because if you're adding lots of 3rd party libraries/ scripts, they all share the same global object, there's the chance of name collisions. This is a real life problem with all the libraries which use
$
as an alias (jQuery, Prototype and more).因为如果你要添加许多第三方库/脚本,它们都共享同一个全局对象,那么就有可能发生名称冲突。这是使用$作为别名(jQuery,Prototype等)的所有库的真实问题。
-
If it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this?
如果在全局范围内拥有vars /函数真的是一个坏主意那么闭包是避免这种情况的最佳方法吗?
x
shouldn't be considered global. It's part of the closure formed by declaring the child functions inside theparent()
function. The problem part of your snippet is thatparent()
is global; what happens if some other code re-declaredparent()
? This would be better:x不应被视为全球性的。它是通过在parent()函数中声明子函数而形成的闭包的一部分。你的代码片段的问题部分是parent()是全局的;如果其他一些代码重新声明parent()会发生什么?这会更好:
(function () { function parent(){ var x = 'some value'; function child1(){ x.someMethod() } function child2(){ x*something; } function child3(){ x+=something; child2() child1() } child3() } parent() }());
The fact
x
is accessible within the child functions isn't bad; you should have written those functions yourself, so you should be aware of the existence ofx
. Bear in mind that if you re-declarex
within those child functions withvar
, you won't affect thex
inparent()
.在子函数中可以访问x的事实并不错;你应该自己编写这些函数,所以你应该知道x的存在。请记住,如果使用var在这些子函数中重新声明x,则不会影响parent()中的x。
更多相关文章
- Javascript学习:案例7--对象属性和方法的遍历、删除、添加.html
- Javascript正则表达式对象和美元符号
- 将JavaScript对象转换为要插入关系数据库的数组
- Javascript对象
- javascript数组和对象是否有设置顺序?
- JavaScript初探系列之面向对象
- 将对象值传递给指令而不是任何其他数据变量
- 对象的属性也要加引号吗
- 在javascript中过滤对象对象(过滤还是减少?)