我正在使用几个需要来回传递变量的函数。我应该使用全局变量还是其他方法?我还要感谢有关如何实施它的一两个例子。
谢谢,Elliot Bonneville
我职能的Psuedocode:
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.
}
答案 0 :(得分:6)
有很多方法可以最大限度地减少您在JavaScript中创建的全局变量的数量。一种方法是将所有变量存储在一个对象下 - 这就是jQuery所做的(技术上jQuery使用两个 - $和jQuery。)
如果您知道自己在做什么,通常不必创建任何全局变量 - 只需将所有代码包装在您立即调用的函数中。
错误示例 - 不必要地污染全局命名空间:
var appleCount = 0;
function addApple() {
appleCount = appleCount + 1;
}
function howManyApples() {
return appleCount;
}
addApple();
alert(howManyApples());
更好的例子 - 只创建一个全局变量:
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
最佳示例 - 不创建全局变量:
(function(){
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
})();
答案 1 :(得分:2)
应该在可重用的脚本中避免使用全局变量。
如果您正在编写仅在一个页面中使用的简单函数,那么使用全局变量没有任何问题。
如果您正在编写可重用的组件或复杂的网页,则应使用闭包或命名空间。
有关更具体的建议,请提供更多详细信息。
修改强>:
您应该创建一个XmlData
类。
例如:
function XmlData(...) {
this.data = ...;
}
XmlData.prototype.doSomething = function(...) {
//Use this.data
}
根据数据的来源,您可能需要创建一个单独的函数来检索数据。
Here是一个很好的解释。
答案 2 :(得分:2)
您尝试做的最佳解决方案是将所有数据包装到对象中,并使您的函数成为对象上的方法:
function MyXMLClass() {
this.data = null;
}
MyXMLClass.prototype = {
GetXML: function() {
this.data = ...;
},
UseXMLData: function() {
// use this.data
},
/* etc. */
};
然后你可以像这样使用它:
var x = new MyXMLClass();
x.GetXML();
x.UseXMLData();
...
答案 3 :(得分:1)
避免全局变量,这是糟糕的编程。尝试将其作为参数传递或使用名称间距来限制其范围。
答案 4 :(得分:1)
创建命名空间,将所有函数放在该命名空间中。
MyNS = {
x: 1, y: 2 // Here you define shared variables
};
MyNS.func1 = function(){}; // Here you define your functions that need those variables