Pregunta

I have a JavaScript app which uses a large amount of global variables (as in, several hundred of them - it's a port of a C program so I didn't write it like that). Obviously this is very bad practice to have so many variables in the Window object, but I'm struggling to come up with a non-verbose way of doing this.
Currently I am thinking this is the way forward:

var myApp = {};

//file1.js:
myApp.variables = (function() {
    var var1, var2, var3;
    var items = new exampleConstructorFunction();
    var etcereta = [];
})();

//file2.js:
myApp.gameplay = (function() {
    //gameplay code
})();

//file3.js:
myApp.scheduling = (function() {
    //timing code
})();

But the problem is, that in order to access any of the variables in myApp.variables from functions defined in gameplay or timing, you would need to specify it as myApp.variables.var1, which is pretty bad for readability when you need to use them often. Any advice?

¿Fue útil?

Solución

You could just store your current globals directly in myApp, or you could avoid that approach and wrap the entire script in an anonymous function and execute it - like (function() { })() then you don't need to namespace your variables to keep them out of global scope.

Otros consejos

If you're just concerned with the length of the variable name, couldn't you just define a reference to it in a local scope?

var v = myApp.variables;

I use ASP, Windows server, MS SQL DB's, but this could also be done in PHP, Linux-based servers, MySQL DB's. You would need to create one or more DB's, then write an ASP script (or PHP script) to store your variables' values in the DB, then (again using an ASP/PHP script) call/use them. Not an easy script-writing task, but plenty of examples avaialble in ASP (PHP forums) that can be adapted. Once scripted and stored in a server side DB, then available for re-use, revision. Can hold many data fields and values. HTH

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top