问题描述
JavaScript:好的部分将这些类型的声明定义为坏的:
JavaScript: The Good Parts defines these kinds of declarations as bad:
foo = value;
这本书说JavaScript 让被遗忘的变量全局化的策略创建很难找到的错误."
The book says "JavaScript’s policy of making forgotten variables global creates bugs that can be very difficult to find."
除了典型全局变量的常见危险之外,这些隐含的全局变量还有哪些问题?
What are some of the problems of these implied global variables other than the usual dangers of typical global variables?
推荐答案
如评论中所述 this answer,设置某些值可能会产生意想不到的后果.
As discussed in the comments on this answer, setting certain values can have unexpected consequences.
在 Javascript 中,这更有可能是因为设置全局变量实际上意味着设置 window
对象的属性.例如:
In Javascript, this is more likely because setting a global variable actually means setting a property of the window
object. For instance:
function foo (input) {
top = 45;
return top * input;
}
foo(5);
这将返回 NaN
,因为您无法设置 window.top
并且乘以 window
对象不起作用.将其更改为 var top = 45
有效.
This returns NaN
because you can't set window.top
and multiplying a window
object doesn't work. Changing it to var top = 45
works.
您无法更改的其他值包括 document
.此外,还有其他全局变量在设置时会做一些令人兴奋的事情.例如,设置 window.status
会更新浏览器的状态栏值,而 window.location
会转到新位置.
Other values that you can't change include document
. Furthermore, there are other global variables that, when set, do exciting things. For instance, setting window.status
updates the browser's status bar value and window.location
goes to a new location.
最后,如果你更新一些值,你可能会失去一些功能.例如,如果您将 window.frames
设置为字符串,则不能使用 window.frames[0]
访问框架.
Finally, if you update some values, you may lose some functionality. If, for instance, you set window.frames
to a string, for instance, you can't use window.frames[0]
to access a frame.
这篇关于“隐含全局变量"有哪些问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!