Javascript Global Variables

How to create a change variable as a global variable?

so something like:

function globVar(variable){
   window.variable;
}

Thus, I could create global variables in automatic mode, and also I could create them for myself easier :)

EDIT

For example, I could create a global variable like this:, globVar('myVariable');then myVariableadded to the global variables.

+3
source share
3 answers

Sorry to say that, but the answers you received are bad habits that you should stay away from. Best programming practice, , , , , /. , , , , / . , .

:

var myNamespace = function(){
  var o = {};
  var globals = {};

  var setGlobVar = function(name, value) {
    globals[name] = value;
  };

  var getGlobVar = function(name) {
    if (globals.hasOwnProperty(name)) {
      return globals[name];
    } else {
      // return null by default if the property does not exist 
      return null;
    }
  };

  o.setGlobVar = setGlobVar;
  o.getGlobVar = getGlobVar;
  return o;
}();

, .

myNamespace.setGlobVar("secret_msg", "Dumbledore dies, so does Hedwig");
myNamespace.getGlobVar("secret_msg");

globals setGlobVar getGlobVar , .


, (.. window) , . , , .

- .

var globals = {};
globals.SECRET_MSG = "Snape is not a traitor"

, globals , .

var myNamespace = {};
myNamespace.globals = {};
myNamespace.globals.SECRET_MSG = "Snape is not a traitor"

. , , , get set -.

+10

globVar('myVar','myVarValue')

function globVar(variable,value){
   window[variable] = value;
}

jsfiddle: http://jsfiddle.net/emQQm/

+1

window.variable = variable;

I don’t understand what “automatic mode” is, so this may not be the way you wanted.

0
source

Source: https://habr.com/ru/post/1774709/


All Articles