When do I use var?

Possible Duplicate:
JavaScript Variable Scope

My understanding it that with in a function if I use var then I have a local variable. If I do not delcare var I now have a global variable.

But what about oustide of functions, what effect does var have?


First of all, it's generally bad practice to use code outside of functions. If nothing else, wrap your code in anonymous functions:

(function(){
    // code
})();

As for what effect var has, it "declares" a variable:

var foo;
alert(foo); // undefined;

vs:

alert(foo); // error: foo is not defined

The reason for this is that the above code is functionally identical to:

alert(window.foo);

without declaring the variable with var , you get a lookup error, the same as trying to access the property of any object that doesn't exist.

Note that one of the oddities of var is that all declarations are pulled to the top of the script, so this will work as well:

alert(foo); // undefined
var foo;

You will also have access to your variable in the window object (though you will also have this by setting the variable without var, eg just foo=42 ):

var foo;
for(var key in window){
   // one of these keys will be 'foo'
}

It is good practice to always use var . Strictly speaking when you are already in the global scope you don't need to but for the sake of code maintainability you should.

Say you have:

foo = 'bar';

But later you decide you want to move this code into a function:

function doSomething() {
    foo = 'bar'; // oops forgot to add var 
}

If you forget to add a var statement you've just created an implicit global. Now if you create a new object in the global scope that is named foo they will cause conflicts with one another.

function doSomething() {
    foo = 'bar'; // Implicit global
}

foo = 'baz';
doSomething();
console.log(foo); // Returns 'bar', not 'baz'

This kind of error is particularly insidious when you forget to use var on something like i in a for loop. Learning to use JSLint can help to avoid these and other problematic logic or syntax errors.


Your question is answered in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable. However, it is recommended to always use var, and it is necessary within functions in the following situations:

  • If a variable in a scope containing the function (including the global scope) has the same name.
  • If recursive or multiple functions use variables with the same name and> intend those variables to be local.
  • Failure to declare the variable in these cases will very likely lead to unexpected results.

    链接地址: http://www.djcxy.com/p/40820.html

    上一篇: 与JavaScript范围混淆

    下一篇: 我什么时候使用var?