I have a variable in a function
that I want to be accessible by other functions. How would you do that?
views:
50answers:
4
+2
A:
You have to specify the object the property (variable) is added to (variables are always properties of some object).
If you want this new variable to be accessible to everything, then you add it to the window object, like this:
window.variablename = 'some value';
Gabriel McAdams
2010-10-23 20:11:25
ah.. i see. so when you declare the variable for the first time you would do that?
chromedude
2010-10-23 20:15:58
yes. That is correct.
Gabriel McAdams
2010-10-23 20:17:18
If you *really* need global state, then define a global namespace instead of cluttering the window object.
Ivo Wetzel
2010-10-23 20:20:31
A:
Or maybe like this:
function funcA() {
if(typeof funcA.variable == 'undefined') {
funcA.variable = 0;
}
else {
funcA.variable++;
}
}
function funcB() {
alert(funcA.variable);
}
funcA();
funcB(); //alerts 0
funcA();
funcA();
funcA();
funcB(); //alerts 3
Pato
2010-10-23 20:20:35
A:
(function () {
var a;
setA(1);
alert(getA()); // 1
function setA(value) {
a = value;
};
function getA() {
return a;
}
})();
eu-ge-ne
2010-10-23 20:26:52
A:
please avoid global variables. if you have asynchronous calls via jquery, the usage of global variables may lead up to ambiguous behaviors.
deepsat
2010-10-23 21:36:02