Javascript: variable scope & the evils of globals
Posted
by
Nick
on Stack Overflow
See other posts from Stack Overflow
or by Nick
Published on 2012-04-12T23:07:35Z
Indexed on
2012/04/12
23:29 UTC
Read the original article
Hit count: 218
I'm trying to be good, I really am, but I can't see how to do it :)
Any advice on how to not use a global here would be greatly appreciated. Let's call the global G.
Function A
Builds G by AJAX
Function B
Uses G
Function C
Calls B
Called by numerous event handlers attached to DOM elements (type 1)
Function D
Calls B
Called by numerous event handlers attached to DOM elements (type 2)
I can't see how I can get around using a global here. The DOM elements (types 1 & 2) are created in other functions (E&F) which are unconnected with A. I don't want to add G to each event handler (because it's large and there's lots of these event handlers), and doing so would require the same kind of solution as I'm seeking here (i.e., getting G to E&F).
The global G, BTW, is an array that is necessary to build other elements as they, in turn, are built by AJAX.
I'm not convinced that a singleton is real solution, either.
Thanks.
© Stack Overflow or respective owner