什么是最好的方法来存储一个值在以后的函数中使用?我听说全球变数是邪恶的 [英] What is the best way to store a value for use in a later function? I'm hearing global variables are evil
问题描述
所以我使用的代码是 http://jsfiddle.net/8j947/10/ ,它会为变量isLive返回true或false值。我如何在后面的函数中使用变量onLive?我在上阅读答案,而不使用全局变量从其他函数访问变量,但是我很难让它正常工作。我所需要的只是存储值,true或false,所以我可以在后面的函数中将它调用到if语句中。任何人都可以给我最简单的方法来做到这一点?有没有一种方法可以将数据存储为对象?
So the code I'm using is at http://jsfiddle.net/8j947/10/ and it returns a value of true or false for the variable isLive. How can I use the variable onLive in a later function? I read the answers at Accessing variables from other functions without using global variables, but I'm having a lot of trouble getting it to work. All I want is to store the value, true or false, so I can call it into an if statement in a later function. Can anyone give me the simplest way to do this? Is there a way to store the data as an object?
推荐答案
全局变量被认为是邪恶的,因为任何函数都可能无意中修改你的变量,这可能会导致一些难以追踪的错误。对于简单的项目来说,这通常不是问题,但应该考虑一下。
Global variables are considered "evil", because any function could inadvertently modify your variable, which can cause some hard-to-track bugs. This usually isn't a problem for simple projects, but it's something you should think about.
保存一个值而不会混淆全局命名空间,从而减少上述错误的风险,您可以创建自己的名称空间对象(您链接的问题中接受答案的选项2)。像这样:
To save a value without muddying the global namespace too much, and thus reduce the risk of the aforementioned bugs, you can create you own "namespace" object (Option 2 of the accepted answer in the question you linked). Like so:
var MyPageData = {};
MyPageData.someProperty = someFunc();
// Later on...
function anotherFunc() {
// Use the data you set...
alert(MyPageData.someProperty);
}
这篇关于什么是最好的方法来存储一个值在以后的函数中使用?我听说全球变数是邪恶的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!