将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

What is the function of the var keyword and when to use it (or omit it)?
var关键字和何时使用它( 或者省略它)?

NOTE :this question was asked from the viewpoint of ECMAScript version 3 or 5.the answers might become outdated with the introduction of new features in the release of ECMAScript 6.

What exactly is the function of the var keyword in Javascript, and what is the difference between :


var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;

and :


someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;

When would you use either one, and why/what does it do?

时间:

If you're in the global scope then there's no difference.

If you're in a function then"var"will create a local variable,"no var"will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it) :


//These are both globals
var foo = 1;
bar = 2;

function()
{
 var foo = 1;//Local
 bar = 2;//Global

//Execute an anonymous function
 (function()
 {
 var wibble = 1;//Local
 foo = 2;//Inherits from scope above (creating a closure)
 moo = 3;//Global
 }())
}

If you're not doing an assignment then you need to use var :


var x;//Declare x

Saying it's the difference between" local and global" isn't entirely accurate.

It might be better to think of it as the difference between" local and nearest".the nearest can surely be global, but that won't always be the case.


/* global scope */
var local = true;
var global = true;

function outer() {
/* local scope */
 var local = true;
 var global = false;

/* nearest scope = outer */
 local =!global;

 function inner() {
/* nearest scope = outer */
 local = false;
 global = false;

/* nearest scope = undefined */
/* defaults to defining a global */
 public = global;
 }
}

When Javascript is executed in a browser, all your code is surrounded by a with statement, like so :


with (window) {
//Your code
}

More info on with - MDN

Since var declares a variable in the current scope, there is no difference between declaring varinside window and not declaring it at all.

The difference comes when you're not directly inside the window, e.g. inside a function or inside a block.

Using var lets you hide external variables that have the same name.in this way you can simulate a"private"variable, but that's another topic.

A rule of thumb is to always use var, because otherwise you run the risk of introducing subtle bugs.

EDIT : after the critiques i received, i would like to emphasize the following :

  • var declares a variable in the current scope
  • The global scope is window
  • Not using var implicitly declares var in the global scope (window )
  • Declaring a variable in the global scope (window) using var is the same as omitting it.
  • Declaring a variable in scopes different from window using varis not the same thing as declaring a variable without var
  • Always declare var explicitly because it's good practice

You should always use the var keyword to declare variables.Why? Good coding practice should be enough of a reason in itself, but declaring a variable without the var keyword means it is declared in the global scope (a variable like this is called an"implied"global).Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines :

Any variable created without the var keyword is created at the global scope and is not garbage collected when the function returns (because it doesn't go out of scope), presenting the opportunity for a memory leak.

So, in short, always declare variables using the var keyword.

Here's quite a good example of how you can get caught out from not declaring local variables with var :


<script>
one();

function one()
{
 for (i = 0;i <10;i++)
 {
 two(i);
 alert(i);
 }
}

function two()
{
 i = 1;
}
</script>

( i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally)

...