Global Variables in Javascript

Declare variable outside of the function…

globalvariables-ee

var oneVariable; 
function setVariable(){ 
oneVariable = "Variable set from within a function!"; 

function getVariable(){ 
alert(oneVariable); // Outputs "Variable set from within a function!" 
}

Or… attach it to the window object

function setValue() { 
window.myValue = "test"; 

function getValue() { 
alert(window.myValue); // "test" (assuming setValue has run) 
}
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s