gpt4 book ai didi

javascript - 为什么在 Javascript 中创建元素全局变量是不好的?

转载 作者:行者123 更新时间:2023-11-28 11:07:54 25 4
gpt4 key购买 nike

我听说在 JavaScript 中将元素设为全局并不是一个好主意。我不明白为什么。这是IE无法处理的吗?

例如:

    div = getElementById('topbar');

最佳答案

我认为这不是一个实现问题,而是一个好与坏实践的问题。通常全局 * 是不好的做法,应该避免(全局变量等),因为您永远不知道项目的范围将如何发展以及您的文件将如何包含。

我不是一个 JS 狂人,所以我无法向您详细说明 JS 事件为何不好,但是 Christian Heilmann talks about JS best practices here ,你可以看一下。还可以尝试谷歌搜索“JS 最佳实践”

编辑:关于全局变量的维基百科,这也可能适用于您的问题:

[global variables] are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, (unless they reside in protected memory) and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See Action at a distance. However, in a few cases, global variables can be suitable for use. For example, they can be used to avoid having to pass frequently-used variables continuously throughout several functions.

通过 http://en.wikipedia.org/wiki/Global_variable

关于javascript - 为什么在 Javascript 中创建元素全局变量是不好的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/794598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com