JavaScript's declared variable promotion often affects our normal access to variables, so close this article so that we can flip through it later.
What is variable elevation
//Variable declaration promotionfunction Test(){ varA= "1"; varF= function(){}; varB= "2"; varC= "3";}//The above code is equivalent tofunction Test(){ varA,F,B,C;A= "1";F= function(){};B= "2";C= "3";}
There are two scenarios for defining variables in JS: (Note that you cannot define a variable without var outside of the method, and that the occurrence of XX is not defined)
- Plus Var, which is a local variable within the method, and a global variable outside the method.
- Within a method, add var to a local variable, and no var is a global variable (after executing the current method)
Variable Promotion Case Study 1
Since the variable A is defined inside the Test1 function,
var='I\'m a in all'functiontest1{ console.log(a) console.log(window.a) var='I\'m a in test1' console.log(a)} test1()
The above code is equivalent to
var='I\'m a in all'functiontest1{ var a console.log// undefined console.log(window.a// I'm a in all(因为window指的是全局环境) ='I\'m a in test1' console.log// I'm a in test1} test1()
Case 2
var='I\'m a in all'functiontest2{ console.log// I'm a in all ='I\'m a in test2'// 这里本来就是赋值,所以上边的a会输出全局变量 console.log// I'm a in test2}test2()
Case 3
functiontest3{ console.log// 报错(Uncaught ReferenceError: a is not defined) ='I\'m a in test3'// 这里本来就是赋值,所以上边的a会输出全局变量 console.log// I'm a in test3}test3()console.log(2// I'm a in test3(本来没有全局变量a,当test3运行时,定义了一个全局变量a,所以这里会输出)
"JavaScript" variable promotion and var for variable promotion