Note that there are some explanatory texts on larger screens.

plurals
  1. POI've Heard Global Variables Are Bad, What Alternative Solution Should I Use?
    primarykey
    data
    text
    <p>I've read all over the place that <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad" rel="noreferrer">global variables are bad</a> and alternatives should be used. In Javascript specifically, what solution should I choose.</p> <p>I'm thinking of a function, that when fed two arguments (<code>function globalVariables(Variable,Value)</code>) looks if Variable exists in a local array and if it does set it's value to <code>Value</code>, else, <code>Variable</code> and <code>Value</code> are appended. If the function is called without arguments (<code>function globalVariables()</code>) it returns the array. Perhaps if the function is fired with just one argument (<code>function globalVariables(Variable)</code>) it returns the value of <code>Variable</code> in the array.</p> <p>What do you think? I'd like to hear your alternative solutions and arguments for using global variables.</p> <h1>How you would use <code>globalVariables();</code></h1> <pre><code>function append(){ globalVariables("variable1","value1"); //globalVariables() would append variable1 to it's local array. }; function retrieve(){ var localVariable1 = globalVariables("variable1"); //globalVariables() would return "value1". }; function retrieveAll(){ var localVariable1 = globalVariables(); //globalVariables() would return the globalVariable()'s entire, local [persistently stored between calls] array. }; function set(){ globalVariables("variable1","value2"); //globalVariables() would set variable1 to "value2". }; </code></pre> <p><strong>Is this a <a href="http://c2.com/cgi/wiki?SingletonPattern" rel="noreferrer">Singleton Pattern</a> BTW?</strong></p> <p>In this specific scenario a function may set a variable at one point in time, and much later another function, maybe when a user submits a form, will need to get that variable. Therefore the first function couldn't pass the variable as an argument to the later function as it would never be called from the first.</p> <p>Thank you, I appreciate all your help!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload