Detailed description of pre-parse in JavaScript

Overview

The JavaScript code is executed by the JavaScript parser in the browser. The JavaScript parser is divided into two steps when running JavaScript code:预解析和代码执行

  1. Our js engine runs js in two steps: pre-analysis and code execution
    (1) pre-analysis: the js engine will promote all vars and functions in js to the top of the current scope
    (2) code execution: write according to the code Order from top to bottom
  2. Pre-analysis is divided into 变量预解析(variable promotion) and 函数预解析(function promotion)
    (1) Variable promotion: all variable declarations are promoted to the front of the current scope, assignment operations are not promoted
    (2) Function promotion: all function declarations Promote to the front of the current scope without calling the function
  3. Function expression call must be written below the function expression

Case study

1. What is the result?

//案例1
var num = 10;
fun();

function fun (){
    
    
	console.log(num);
	var num = 20;
}
//相当于执行了以下的操作
var num;
function fun (){
    
    
	var num;
	console.log(num);
	num = 20;
}
num = 10;
fun();

2. What is the result?

var num = 10;
function fun (){
    
    
	console.log(num);
	var num = 20;
	console.log(num);
}
fun();
//相当于以下代码
var num;
function fun (){
    
    
      var num 
	console.log(num);
	 num = 20;
	console.log(num);
}
num = 10;
fun();

3. What is the result?

f1();
console.log(c);
console.log(b);
console.log(a);
function f1 (){
    
    
	var a=b=c=9;
console.log(a);
console.log(b);
console.log(c);
}

//相当于以下代码
function f1 (){
    
    
	var a;
    a = b = c = 9;
	//相当于 var a=9; b=9; c=9;    b和c直接赋值前面 没有var声明 当全局变量看
	
console.log(a); //9
console.log(b); //9
console.log(c); //9
}
f1();
console.log(c); //9
console.log(b); //9
console.log(a); //打印报错 函数中的 var a 为局部变量无法打印

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/107752415