简体   繁体   中英

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.

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

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. :)

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. This will result in DOM manipulation for remaining two as well. Like any other language/technology, this is not the problem of technology itself. It is the problem caused by not following good coding ethos. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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