简体   繁体   中英

DOM-Objects declared as JavaScript global variables

Would it be a good practice to declare certain DOM-Objects as global JavaScript variables within a namespace?

Something like this:

var MyNS = {};

$(document).ready(function(){
    MyNS.domObject1 = $('#id1');
    MyNS.domObject2 = $('#id2');
});

Some things to consider:

1) Creating global variables in JavaScript is not a good practice, every global variable is actually a property of the window global object, which already has a lot of properties. This means that, if you add global variables you might be messing with existing variables, or some other code may overwrite your variables.

Solutions for this: Store all the global variables you need on a single object, and make sure nothing else in tha page will use that object. Or don't even use global variables at all.

2) Why would you need to store those elements globally if you already can access them with the IDs? Even if you want to have a direct reference somewhere, you can store them as variables of the $(document).ready funciton, and they'll be visible to all te functions declared there.

3) To fully prevent the use of global variables you can smartly wrap your codes in anonymous auto-executable functions like this one:

(function () { ... }());

All the variable you declare inside this type of functions will be only be visible inside that function, and the function will execute inmediatelly, and through garbage-collection you can solve any performance issues realated to having too much references to DOM objects, just by using this anonymous functions.

4) If all that fails, then yes, you're making the right decision by storing all the elements in an object, instead of making a global variable for each element.

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