Easy global variables in Javascript

Posted: December 30, 2009 in Code, Firefox, Internet, Software
Tags: , , ,

I just wanted to make a quick post about this.

Awhile back I was working on a homework assignment for my Web Design class I needed global variables. Now for those of you who don’t know what a global variable is, a global variable is a variable that can be accessed anywhere in a program, no matter where it is called. Now the way that I knew you could do this was to have a dollar sign ($) before the variable name, thus making it global. Here’s what something like that would look like:

function hello_world
{
$hello_world = “hello world”;
}

function goodbye_everyone
{
alert(“I said: “+ $hello_world+ “And now I’m saying goodbye!”);
}

The above code snippet would work, but only because I have the variable $hello_world as a global variable.

Now what I wanted was an easier way to do this. Because once you declare a variable global with the dollar sign, it has to be written like that throughout the whole program. Not such a big deal, except  I was already over 1,000 lines into my code, so it became a big deal. I went searching through the internet for a better way to do this, and found it.

It turns out that when you declare a variable, it gets appended to the ‘window’ object. So what did I need to do to access this variable? Let me show you:

function hello_world
{
hello_world = “hello world”;
}

function goodbye_everyone
{
alert(“I said: “+window.hello_world+”And now I’m saying goodbye!”);
}

Notice that all I had to do to use a global variable in this above example was add ‘window.’ to the beginning of the variable. I didn’t have to change the first invocation of the variable or anything. All I had to do was type in window.hello_world to use this variable as a global variable. Very, very, very easy to use and much much better than creating special global variables. This way if you start a program you can add the capabilities to use global variables without having to backtrack through your program.

And yes, this is cross browser. I’ve tested it in Firefox, Chrome and Internet Explorer.

If you have any questions I’d be happy to answer them.

Happy coding!

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