Ell*_*lle 3 javascript global-variables
我正在使用几个需要来回传递变量的函数.我应该使用全局变量还是其他方法?我还要感谢一个或两个如何实现它的例子.
谢谢,Elliot Bonneville
我的函数的伪代码:
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.
}
Run Code Online (Sandbox Code Playgroud)
正如您可能猜到的那样,全局变量被认为是坏的.页面上的任何其他代码都可以修改它们 - 通常是因为另一个程序员意外地选择了相同的名称.你可以尝试通过选择真正奇怪的名字来缓解这种影响,但是你会得到一堆非常奇怪的名字.
有很多方法可以最小化您在JavaScript中创建的全局变量的数量.一种方法是将所有变量存储在单个对象下 - 这就是jQuery所做的(技术上jQuery使用两个 - $和jQuery.)
如果您知道自己在做什么,通常不必创建任何全局变量 - 只需将所有代码包装在您立即调用的函数中.
错误示例 - 不必要地污染全局命名空间:
var appleCount = 0;
function addApple() {
appleCount = appleCount + 1;
}
function howManyApples() {
return appleCount;
}
addApple();
alert(howManyApples());
Run Code Online (Sandbox Code Playgroud)
更好的例子 - 只创建一个全局变量:
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
Run Code Online (Sandbox Code Playgroud)
最佳示例 - 不创建全局变量:
(function(){
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3164 次 |
| 最近记录: |