简体   繁体   中英

Should I use a global variable and if not, what instead? (Javascript)

I'm working with several functions which need to pass a variable back and forth. Should I use a global variable or another method instead? I would also appreciate an example or two on how to implement it.

Thanks, Elliot Bonneville

Psuedocode of my functions:

function GetXML() {//this would be a function which reads in an XML file.
                  //Preferably it would also generate or set an object to hold the XML data.
}

function UseXMLData() { //I would use the XML data here.
}

function UseXMLDataHereAsWell() { //And here as well.
}

Global variables are, as you probably guessed, considered bad. Any other code on the page can modify them - often because another programmer accidentally picks the same name. You can try to mitigate this effect by choosing really strange names, but then you get a bunch of really strange names.

There are a lot of ways to minimize the number of global variables you create in JavaScript. One way is to store all your variables under a single object - that's what jQuery does (Technically jQuery uses two - $ and jQuery.)

If you know what you're doing, you often don't have to create any global variables - just wrap all your code in a function that you invoke immediately.

Bad example - pollutes the global namespace unnecessarily:

var appleCount = 0;

function addApple() {
  appleCount = appleCount + 1;
}

function howManyApples() {
  return appleCount;
}

addApple();
alert(howManyApples());

Better example - only creates one global variable:

var appleCounter = {
  count: 0,
  add: function() {
    this.count = this.count + 1;
  },
  howMany: function() {
    return this.count;
  }
};

appleCounter.add();
alert(appleCounter.howMany());

Best example - creates no global variables:

(function(){
  var appleCounter = {
    count: 0,
    add: function() {
      this.count = this.count + 1;
    },
    howMany: function() {
      return this.count;
    }
  };

  appleCounter.add();
  alert(appleCounter.howMany());
})();

Global variables should be avoided in reusable scripts.

If you're writing simple functions that will only be used in one page, there's nothing wrong with using globals.

If you're writing a reusable component or a complex web page, you should use closures or namespaces instead.

For more specific advice, please provide more detail.

EDIT : You should create an XmlData class.

For example:

function XmlData(...) { 
    this.data = ...;
}
XmlData.prototype.doSomething = function(...) { 
    //Use this.data
}

Depending on how what your data comes from, you may want to make a separate function to retrieve the data.

Here is a good explanation.

The best solution for what you're trying to do would be to wrap all your data into an object and make your functions be methods on the object:

function MyXMLClass() {
  this.data = null;
}

MyXMLClass.prototype = {
  GetXML: function() {
    this.data = ...;
  },

  UseXMLData: function() {
    // use this.data
  },

  /* etc. */
};

And then you can just use it like this:

var x = new MyXMLClass();
x.GetXML();
x.UseXMLData();
...

Avoid global variables, it's bad programming. Try pass it as an argument or use name spacing to restrict its scope.

Create a namespace, put all your functions within that namespace.

MyNS = {
    x: 1, y: 2 // Here you define shared variables
};

MyNS.func1 = function(){}; // Here you define your functions that need those variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM