tags:

views:

119

answers:

2

I have a javascript function to generate a var. That function is activated by an onclick button event.

After that var is generated, I need to use it as a global var so that other js processes can use that var.

How do I do it?

+2  A: 

You should be able to add the variable's value to a property of the global window object:

window.yourVarName = yourVarName;

Then the other functions will be able to access yourVarName simply by referencing yourVarname directly. There will be no need to use window.yourVarName.

However keep in mind that in general, global variables are evil.

Daniel Vassallo
why is it evil? Mind explain a little?
Eric Sim
@Eric: http://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use
Daniel Vassallo
in Javascript, by default it is windows object,why again prefixing it with window
Srinivas Reddy Thatiparthy
@Srinivas: Primarily clarity, to avoid the horror of implicit globals.
T.J. Crowder
@Srinivas makes the assignment clearer, not including it would make it ambiguous were that variable is declared.
roryf
@Srinivas: Because if I understood the OP's context correctly, the variable `yourVarname` will be defined in local function scope as well.
Daniel Vassallo
If you assign a variable inside local function scope without the `var` keyword, it gets assigned to the window object (in FF at least) so the behaviour is the same.
roryf
@roryf: Yes true. But I think the OP had it as a local variable. It could be a function argument for example.
Daniel Vassallo
A: 

Declare the variable outside the scope of the function:

var foo = null;

function myClickEvent() {
    foo = someStuffThatGetsValue;
}

Better yet, use a single global variable as the namespace for your application, and store the value inside that:

var MyApp = {
    foo: null
};

function myClickEvent() {
    MyApp.foo = someStuffThatGetsValue;
}

The function itself could even be included in there

roryf