我应该使用全局变量吗?如果不是,反而是什么? (JavaScript)的 [英] Should I use a global variable and if not, what instead? (Javascript)

查看:87
本文介绍了我应该使用全局变量吗?如果不是,反而是什么? (JavaScript)的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理几个需要来回传递变量的函数。我应该使用全局变量还是其他方法?

感谢,Elliot Bonneville



Psuedocode of我的函数:

 函数GetXML(){//这是一个读取XML文件的函数。 
//最好还会生成或设置一个对象来保存XML数据。
}

函数UseXMLData(){//我会在这里使用XML数据。
}

函数UseXMLDataHereAsWell(){//在这里也是如此。


解决方案

'试图做的就是将所有的数据包装到一个对象中,并将你的函数作为对象的方法:

 函数MyXMLClass(){
this.data = null;
}

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

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

/ *等* /
};

然后您可以像这样使用它:

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


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

解决方案

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

这篇关于我应该使用全局变量吗?如果不是,反而是什么? (JavaScript)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆