[Javascript] Changing an Objects ID and Name

Jonathan Buchanan jonathan.buchanan at gmail.com
Thu Sep 7 04:16:26 CDT 2006


> I thought it was the opposite so that something declared as var will be
> "global". For example:
>
> var thisVariable = 50;
> thisNoVariable = 5;
>
> trythis();
>
> trythisno();
>
> function trythis() {
>         alert(thisVariable);
> }
>
> function trythisno() {
>         alert(thisNoVariable);
> }
>
> I have not tested this, but I do believe there will be an error in the
> function trythisno().
>
> /Peter

Have a look at the documentation for the var operator:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:var

In your example, you've created two variables in the global scope, so
both functions will work. As you can read in the documentation, it
doesn't matter whether you use "var" or not when declaring functions
in the global scope - you're already in the global scope, so by using
the var operator you're just explicitly saying "I belong to the
current scope, which is the global scope" (as with thisVariable)
rather than saying "I belong to the default scope, which is the global
scope" (as with thisNoVariable).

What we're really interested in is the effect var has in a function.
If you don't use the var operator, any variables you declare in a
function get the default scope, which is the global scope. This is why
it's important to use var to declare local variables in functions.

function testScoping1()
{
    cheese = 5;
}

testScoping1();

alert(typeof(cheese)); // Produces "number" - the cheese variable is
now in the global scope!

function testScoping2()
{
    var toast = 10;
}

testScoping2();

alert(typeof(toast)); // Produces "undefined" - the toast variable was
local to the function during its execution

Jonathan.



More information about the Javascript mailing list