The scope and promotion of var

1. Variable promotion

No matter where the actual declaration is, the declaration of the variable will be promoted to the top of the function or global scope (and the assignment operation is still in the original position)

2. Variable scope

In ES5, js has only two forms of scope: global scope and function scope
1. The global scope is actually the scope of the global object, which can be accessed anywhere
2. Variables outside the function can be accessed within the function, The variables inside the function cannot be accessed outside the function

  var i = 2;   //全局变量,全局作用域
  function outer(){
    
       //定义外部函数
	 console.log(i);  //访问全局变量  2
	 function inner(){
    
     //定义内部函数
		 console.log(i);   //访问全局函数 2
	 }
	 inner(); 
  }
  outer();
  console.log(i); //2

3. Case

  //函数作用域内的变量外部是无法访问的
   function foo() {
    
    
      // 函数作用域内var会使变量提升到函数最顶部
       var name = 'nick'
   }
   foo()
   console.log(name)   //会报错
   // 函数内声明相同的变量
   var name = 'nick';
   function foo() {
    
    
      var name = 'nancy';
      console.log(name);
   }
   foo(); // => 'nancy'
   console.log(name); // => 'nick'
    //在控制语句内声明的变量,在控制语句外面也可以使用
   if (true) {
    
    
       var a = 1
   }
   for (var i = 1; i < 10; i++) {
    
     }
   console.log(a, i);  // => 1  10

    // 在控制语句内声明一个与外部同名的变量。
   var b = 1;
   if (true) {
    
    
       var b = 10; // 与外部 x 变量同名
   }
   console.log(b); // => 10

Guess you like

Origin blog.csdn.net/m0_48076809/article/details/109018504