views:

50

answers:

4

I have a variable in a function that I want to be accessible by other functions. How would you do that?

+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
ah.. i see. so when you declare the variable for the first time you would do that?
chromedude
yes. That is correct.
Gabriel McAdams
If you *really* need global state, then define a global namespace instead of cluttering the window object.
Ivo Wetzel
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
A: 
(function () {
    var a;

    setA(1);
    alert(getA()); // 1

    function setA(value) {
        a = value;
    };

    function getA() {
        return a;
    }
})();
eu-ge-ne
This is no different than `window.a = 1` or just using non declared global variables.
MooGoo
@MooGoo thanks, fixed
eu-ge-ne
A: 

please avoid global variables. if you have asynchronous calls via jquery, the usage of global variables may lead up to ambiguous behaviors.

deepsat