“隐含全局变量"有哪些问题?

What are some of the problems of quot;Implied Global variablesquot;?(“隐含全局变量有哪些问题?)
本文介绍了“隐含全局变量"有哪些问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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.

这篇关于“隐含全局变量"有哪些问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)