今天备忘的是Variable Declaration and Variable Scope。今天直接上原汁原味的代码例子反而觉得更清楚:
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"
scope = "global"; // Declare a global variable, even without var. function checkscope2() { scope = "local"; // Oops! We just changed the global variable. 最重要的是这里,在函数体内没使用var,则修改的是全局变量。 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.
//这里主要讲函数可以嵌套
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(); } checkscope() // => "nested scope"
//这个例子很重要,说明了变量声明范围遍布了整个函数体,所以局部变量屏蔽了全局变量,但是注意这里的变量初始化,他发生在声明代码之后的范围,之前的范围是没初始化的。
var scope = "global"; function f() { console.log(scope); // Prints "undefined", not "global" var scope = "local"; // Variable initialized here, but defined everywhere console.log(scope); // Prints "local" }