为什么在JavaScript中使元素全局变量是不好的? [英] Why is it bad to make elements global variables in Javascript?

查看:188
本文介绍了为什么在JavaScript中使元素全局变量是不好的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如:

  div = getElementById('topbar'); 


解决方案

我不认为这是一个实现问题,更好的vs坏习惯问题。通常,全局*是不好的做法,应该避免(全局变量等),因为您从来不知道项目的范围将如何演变以及文件的包含方式。



我不是一个大的JS怪胎,所以我将无法给你的具体细节为什么JS事件是坏的,但 Christian Heilmann在这里谈论JS最佳做法,你可以看一下。另请尝试谷歌搜索JS最佳实践



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




[全局变量]通常是
,因为它们的非局部性被认为是非常糟糕的做法:
全局
变量可以从任何地方修改
,(除非它们位于
受保护的内存中),并且
程序的任何部分可能依赖于它。因此,一个全局的
变量具有无限的
潜力来创建相互
依赖关系,并且添加共同的
依赖关系会增加复杂性。看到
远处的动作。然而,在
的少数情况下,全局变量可以是
适合使用。例如,他们可以使用
来避免在多个函数中不断地通过
常用的变量


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


I've heard that it's not a good idea to make elements global in JavaScript. I don't understand why. Is it something IE can't handle?

For example:

    div = getElementById('topbar');

解决方案

I don't think that's an implementation issue, but more a good vs bad practice issue. Usually global * is bad practice and should be avoided (global variables and so on) since you never really know how the scope of the project will evolve and how your file will be included.

I'm not a big JS freak so I won't be able to give you the specifics on exactly why JS events are bad but Christian Heilmann talks about JS best practices here, you could take a look. Also try googling "JS best practices"

Edit: Wikipedia about global variables, that could also apply to your problem :

[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.

via http://en.wikipedia.org/wiki/Global_variable

这篇关于为什么在JavaScript中使元素全局变量是不好的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆