最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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.
}

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.
}
Share Improve this question edited Nov 16, 2010 at 3:04 Elliot Bonneville asked Nov 16, 2010 at 2:49 Elliot BonnevilleElliot Bonneville 53.4k23 gold badges100 silver badges124 bronze badges 1
  • 2 Can you post an example of the kind of functions you're talking about? – casablanca Commented Nov 16, 2010 at 2:52
Add a ment  | 

5 Answers 5

Reset to default 6

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());
})();

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();
...

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 ponent or a plex 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 es from, you may want to make a separate function to retrieve the data.

Here is a good explanation.

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

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

发布评论

评论列表(0)

  1. 暂无评论