JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

3.10 Variable Scope

3.10 Variable Scope


The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable:

var scope = "global"; // Declare a global variable

function checkscope() {

var scope = "local"; // Declare a local variable with the same name

return scope; // Return the local value, not the global one

}

checkscope() // => "local"

Although you can get away with not using the var statement when you write code in the global scope, you must always use var to declare local variables. Consider what happens if you don’t:

scope = "global"; // Declare a global variable, even without var.

function checkscope2() {

scope = "local"; // Oops! We just changed the global variable.

myscope = "local"; // This implicitly declares a new global variable.

return [scope, myscope]; // Return two values.

}

checkscope2() // => ["local", "local"]: has side effects!

scope // => "local": global variable has changed.

myscope // => "local": global namespace cluttered up.

Function definitions can be nested. Each function has its own local scope, so it is possible to have several nested layers of local scope. For example:

var scope = "global scope"; // A global variable

function checkscope() {

var scope = "local scope"; // A local variable

function nested() {

var scope = "nested scope"; // A nested scope of local variables

return scope; // Return the value in scope here

}

return nested();

}

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27614.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1