javascript中的变量作用域以及变量提升详细介绍 |
变量作用域 变量作用域分为局部作用域和全局作用域 。 局部变量(处于函数级别的作用域) 函数级别作用域的一个例子: 复制代码 代码如下: var name = "Richard"; function showName () { var name = "Jack"; // local variable; only accessible in this showName function console.log (name); // Jack } console.log (name); // Richard: the global variable 没有块级作用域: 复制代码 代码如下: var name = "Richard"; // the blocks in this if statement do not create a local context for the name variable if (name) { name = "Jack"; // this name is the global name variable and it is being changed to "Jack" here console.log (name); // Jack: still the global variable } // Here, the name variable is the same global name variable, but it was changed in the if statement console.log (name); // Jack // 不要忘记使用var关键字 全局变量 每一个在函数外部声明或者定义的变量都是一个全局对象,所以这个变量可以在任何地方被使用,例如: 复制代码 代码如下: // name and sex is not in any function var myName = "zhou"; var sex = "male"; //他们都处在window对象中 console.log(window.myName); //paul console.log(sex in window); //true 如果一个变量第一次初始化/声明的时候没有使用var关键字,那么他自动加入到全局作用域中 。 复制代码 代码如下: function showAge(){ //age初始化时没有使用var关键字,所以它是一个全局变量 age = 20; console.log(age); } showAge(); //20 console.log(age); //因为age是全局变量,所以这里输出的也是20 setTimeout中的函数是在全局作用域中执行的 setTimeout中的函数所处在于全局作用域中,所以函数中使用this关键字时,这个this关键字指向的是全局对象(Window): 复制代码 代码如下: var Value1 = 200; var Value2 = 20; var myObj = { Value1 : 10, Value2 : 1, caleculatedIt: function(){ setTimeout(function(){ console.log(this.Value1 * this.Value2); }, 1000); } } myObj.caleculatedIt(); //4000 为了避免对全局作用域的污染, 所以一般情况下我们尽可能少的声明全局变量 。 复制代码 代码如下: function showName () { console.log ("First Name: " + name); var name = "Ford"; console.log ("Last Name: " + name); } showName (); // First Name: undefined // Last Name: Ford // The reason undefined prints first is because the local variable name was hoisted to the top of the function // Which means it is this local variable that get calls the first time. // This is how the code is actually processed by the JavaScript engine: function showName () { var name; // name is hoisted (note that is undefined at this point, since the assignment happens below) console.log ("First Name: " + name); // First Name: undefined name = "Ford"; // name is assigned a value // now name is Ford console.log ("Last Name: " + name); // Last Name: Ford } 函数声明会覆盖变量声明 复制代码 代码如下: // Both the variable and the function are named myName var myName;? function myName () { console.log ("Rich"); } // The function declaration overrides the variable name console.log(typeof myName); // function 但是,如果这个变量或者函数其中是赋值了的,那么另外一个将无法覆盖它: 复制代码 代码如下: // But in this example, the variable assignment overrides the function declaration var myName = "Richard"; // This is the variable assignment (initialization) that overrides the function declaration. function myName () { console.log ("Rich"); } console.log(typeof myName); // string 最后一点, 在严格模式下,如果没有先声明变量就给变量赋值将会报错! |