简体   繁体   English

JavaScript-将元素存储在全局变量中

[英]JavaScript - storing elements in global variables

I know that global variables are considered evil in JS.However I'm used to store DOM Elements in global variables for easy accessibility. 我知道在JS中全局变量被认为是邪恶的,但是为了方便访问,我习惯将DOM元素存储在全局变量中。

Let's say, that alternative to global variables are for example closures.Because they offer way to create scope which disallows external influences to modify inner variable.But is this necessary in case of DOM Elements? 假设全局变量的替代方法是闭包,因为它们提供了创建范围的方法,该范围不允许外部影响来修改内部变量,但是在DOM Elements的情况下是否有必要? Is there any danger or disadvantage of storing elements in global variables? 在全局变量中存储元素是否存在任何危险或不利之处?

Since I've found article explaining why global variables are evil, instead of global variables I'm using manual reference. 自从我找到了解释为什么全局变量为何有害的文章后,我使用的是手册参考。

So instead of: 所以代替:

e = document.getElementById('example');
e.value = 'abc';

I use: 我用:

function e(id)
{

 return document.getElementById(id);
}
e('example').value = 'abc';

Is this legit alternative? 这是合法的选择吗?

DOM Elements, by their own nature are global. DOM元素本身具有全球性。

Becuase your document is a global object they are accessible from anywhere in the app anyway. 由于您的文档是全局对象,因此无论如何都可以从应用程序中的任何位置访问它们。

What you're doing is good in a way that it facilitates the reuse of code but it doesn't solve any of the problems of global scope - meaning, your DOM elements are any accessible throughout the app whether you employ this strategy or not. 您正在做的事情是好的,它可以促进代码的重用,但不能解决任何全局范围的问题-也就是说,无论您是否采用此策​​略,DOM元素在整个应用程序中都是可访问的。 :) :)

Another problem however, is that if you store reference to the same DOM object in three different variables for example, and you alter one of those three variables. 但是,另一个问题是,例如,如果将对同一DOM对象的引用存储在三个不同的变量中,那么您将更改这三个变量之一。 This will result in DOM manipulation for remaining two as well. 这也将导致对其余两个对象的DOM操作。 Like any other language/technology, this is not the problem of technology itself. 像任何其他语言/技术一样,这也不是技术本身的问题。 It is the problem caused by not following good coding ethos. 这是由于未遵循良好的编码方式引起的问题。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM