当前位置:网站首页>Variable promotion and function promotion in JS

Variable promotion and function promotion in JS

2022-07-04 13:58:00 51CTO

js Variable promotion and function promotion in

 stay js The printed value often appears after the variable is operated in undefined The phenomenon of . In fact, the reason is because js There is a function called variable Promotion . give an example :
	var data="lyyyyy";
	getData();
	function getData(){
		// First printing 
		console.log("data The value is : ", data);
		var	data="yyyyyyy";
		// Second printing 
		console.log("data The value is : ", data);
	}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

The first value printed is undefined, The second printed value is yyyyy.

 reason :
 In execution getData() Method will first promote the declaration of variables inside the function to the first step .
	 Then declare the function inside the function ( If there is a function inside the function ).
	 Then the code will be executed in the logical order inside the method . The first two steps are just statements !!!
 Seeing here, you should already know why there are such results as above .

The actual method internal code execution order should be like this :

	function getData(){
		// One . Declare variables 
		var	data;
		// Two . Declare functions ( If there is a function inside the function )

		// 3、 ... and . Execute in the order of the code 
		console.log("data The value is : ", data);
		data="yyyyyyy";
		// Second printing 
		console.log("data The value is : ", data);
	}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

When you see the execution order of the split code, you are not confused about the results .

Why is there a variable increase

So why is there a phenomenon of variable Promotion ?

Actually js Like any other language , You have to go through the compilation and execution phases . and js During the compilation phase , All variable declarations will be collected and declared in advance , Other statements do not change their order , therefore , During the compilation phase , The first step has been carried out , The second step is to execute the statement at the execution stage .

summary

1.js Will promote the declaration of variables to js Top execution , So for this statement :var a = 2; Actually js It will be divided into var a; and a = 2; Two parts , And will var a This step is lifted to the top to perform .

2. The essence of variable promotion is actually due to js When the engine compiles , All variables are declared , So when executing , All variables have been declared .
3. When multiple variables with the same name are declared , Function declarations override other declarations . If there are multiple function declarations , The last function declaration overrides all previous declarations .

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041233085954.html