Reputation: 52047
I have a fairly large script that contains about 60 global variables. I'm thinking about using the namespace pattern to encapsulate my script and have only one global variable that references one object.
Even though this pattern is considered best practice, I'm also thinking about an alternative: storing the global variables inside the DOM, in hidden divs, and accessing them with $('#MyGlobalVar1').text()
. Is this a good idea or not?
Thanks for your suggestions.
Upvotes: 1
Views: 2925
Reputation: 360066
No, this is not a good idea.
It pollutes the DOM with non-semantic data, and is less efficient as well. That's even worse than polluting the global JS namespace, and worse still, it only allows you to store strings.
Upvotes: 9
Reputation: 236202
Even if I would recommend you to use a namespace object to hold and reference your data, you can simply put an outer self-invoking function around your code to prevent clobbering the global object.
So you go from
var global1 = true,
global2 = true;
into
(function() {
var global1 = true,
global2 = true;
// rest of all app logic
}());
Beyond that, since you're using jQuery you also might to use jQuerys .data()
method. It's designed to reference data for a specific node, but it's internally stored into an ECMAscript object also.
Upvotes: 3