Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a JavaScript local variable into a global variable

Tags:

javascript

I have a JavaScript function to generate a variable. That function is activated by an onclick button event.

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

How do I do it?

like image 427
Eric Sim Avatar asked May 07 '10 11:05

Eric Sim


People also ask

How can you convert a local variable to a global variable?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How can you force a variable in a function to refer to the global variable?

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.

How do I create a global object in JavaScript?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object.


2 Answers

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.

like image 124
Daniel Vassallo Avatar answered Sep 28 '22 03:09

Daniel Vassallo


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 ("MyApp") 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.

like image 24
roryf Avatar answered Sep 28 '22 03:09

roryf