js中的var定义局部变量

 

摘自《O'Reilly - Learning JavaScript》

 

When you use var with a variable, you’re defining the variable with local scope, which means you can access them only within the function in which you’ve defined them. If I didn’t use var, the variable msg would be global and would have scope inside and outside the function.

Using a global variable in a local context isn’t a bad thing—and it may be necessary at

times—but it isn’t a good practice, and you should avoid it if possible.

 

Here are the rules regarding scope:

• If you declare a variable with the var keyword in a function or block of code, its

use is local to that function.

• If you use a variable without declaring it with the var keyword, and a global variable

of the same name exists, the local variable is assumed to be the already existing

global variable.

• If you declare a variable locally with a var keyword, but you do not initialize it (i.e.,

assign it a value), it is local and accessible but not defined.

• If you declare a variable locally without the var keyword, or explicitly declare it

globally but do not initialize it, it is accessible globally, but again, it is not defined.

 

 

你可能感兴趣的:(局部变量)