search
HomeWeb Front-endJS TutorialWhat is JavaScript preinterpretation? JavaScript pre-interpretation parsing (with code)

The content of this article is about what is JavaScript pre-interpretation? The analysis of JavaScript pre-interpretation (with code) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

JavaScript is an interpreted language. Running JavaScript code requires two stages

  • Compilation stage: The compilation stage is what we often call JavaScript pre-interpretation ( Preprocessing) stage, at this stage the JavaScript interpreter will complete the conversion of JavaScript script code into bytecode

  • Execution stage: During the compilation stage, the JavaScript interpreter converts the bytecode into bytecode with the help of the execution environment Generate mechanical code and execute it sequentially from top to bottom

This article focuses on pre-interpretation. The framework diagram is as follows:

What is JavaScript preinterpretation? JavaScript pre-interpretation parsing (with code)

1. What is pre-interpretation

Pre-interpretation:Before JavaScript code is executed, the browser will first declare or define all vars and functions in advance by default

1. Understand declarations and definitions

Declaration (declare): For example, var num;=> tells the browser that there is a num variable in the global scope; if a variable is only declared but There is no assignment, and the default value is undefined

Definition (defined): For example, num=12;=> assign a value to our variable.

2. For those with var and function keywords, the operations are different during pre-interpretation.

var => is only declared in advance during pre-interpretation.

function => During pre-interpretation, all declarations and definitions in advance are completed

3. Pre-interpretation only occurs in the current scope.

For example: only the contents under window will be pre-interpreted at first, and the functions in the function will be pre-interpreted only when the function is executed.

2. Scope chain

1 .How to distinguish between private variables and global variables?

1) Variables declared in the global scope (when pre-interpreted) are global variables

2) Only function execution will produce private effects Domains, such as for(){}, if(){} and switch(){} will not generate private scope

3) Variables declared in "private scope" (var declaration)" and "function parameters" are both private variables. In the private scope, when the code is executed and a variable is encountered, first we need to determine whether it is a private variable. If it is a private variable, it has no relationship with the outside; if it is not private, it will go to Search the upper-level scope of the current scope. If there is no upper-level scope, continue to search until the window is found. This is the scope chain.

Let’s take an example to distinguish between private variables and global variables:

//=>变量提升:var a;var b;var c;test=AAAFFF111;
var a=10,b=11,c=12;
function test(a){
//=>私有作用域:a=10 var b;
a=1;//=>私有变量a=1
var b=2;//=>私有变量b=2
c=3;//=>全局变量c=3
}
test(10);
console.log(a);//10
console.log(b);//11
console.log(c);//3

One criterion for judging whether a private variable is a variable declared by var in a function and a formal parameter of the function They are all private variables. In this question, a is a formal parameter in the test function and the variable b defined by var b is a private variable.

2. Function parameter passing

This is because when the function is executed, a new private scope will first be formed, and then executed according to the following steps:

1) If there are formal parameters, assign values ​​to the formal parameters first

2) Perform pre-interpretation in the private scope

3) The code in the private scope is executed from top to bottom

Let’s look at an example

var total=0;
function fn(num1,num2){
console.log(total);//->undefined 外面修改不了私有的
var total=num1 +num2;
console.log(total);//->300
}
fn(100,200);
console.log(total);//->0 私有的也修改不了外面的

3. Classification of memory in JS

Stack memory: used Provide an environment for JS code execution, that is, scope (global scope/private scope)
Heap memory: used to store values ​​of reference data types. Objects store attribute names and attribute values, and functions store code strings.

3. The difference between var and without var in the global scope

Let’s first look at the following two examples:

//例题1
console.log(num);//->undefined
var num=12;
//例题2
console.log(num2);//->Uncaught ReferenceError:num2 is not defined 
num2=12;//不能预解释

When you see var num=12 , you might think it is just a statement. But JavaScript will actually treat it as two declaration statements: var num; and num=12; The first definition statement is made in the pre-interpretation stage. The second assignment statement will be left in place waiting for the execution phase . num2=12 is equivalent to adding an attribute name called num2 to window, and the attribute value is 12; and var num=12 is equivalent to adding a global variable num to the global scope. It is also equivalent to adding a global variable num to window. The attribute name is num2, and the attribute value is 12. The biggest difference between the two: the one with var can be pre-interpreted, so no error will be reported when executed before the assignment; the one without var cannot be pre-interpreted, and an error will be reported when executed before;

Next we give an example:

//例题1
var total=0;
function fn(){
console.log(total);//undefined
var total=100;
}
fn();
console.log(total);//0
//例题2
var total=0;
function fn(){
console.log(total);//0
total=100;
}
fn();
console.log(total);//100

In Example 1, the var variable can be pre-interpreted in the private scope, so the value printed by the first console is undefined. If a variable that appears in the private scope is not private, search in the upper-level scope. If there is no upper-level scope, continue to search upward until you find the window.. In Example 2, the variable without var is not private, so Go to your superiors

4. Pre-explain the five major signs of being unethical

1. When pre-explaining, regardless of whether your conditions are established, you must declare the var in advance.

Please look at the following example question:

if(!("num" in  window)){
var num=12;//这句话会被提到大括号之外的全局作用域:var num;->window.num; 
}
console.log(num);//undefined

2.预解释的时候只预解释”=”左边的,右边的值,不参与预解释

请看下面这道例题:

fn();//报错
var fn=function (){  //window下的预解释:var fn;
console.log("ok");
};

3.自执行函数:定义和执行一起完成了。

自执行函数定义的那个function在全局作用域下不进行预解释,当代码执行到这个位置的时候定义和执行一起完成了。常见有以下几种形式:

(function(num){})(10);
~function(num){}(10);
+function(num){}(10);
-function(num){}(10);
!function(num){}(10);

4.函数体中return下面的代码虽然不再执行了,但是需要进行预解释;return后面跟着的都是我们返回的值,所以不进行预解释;

function fn(){
//预解释:var num;
console.log(num);//->undefined
return function(){};
var num=100;
}

5.函数声明和变量声明都会被提升。但是一个值得注意的细节(这个细节可以出现在有多个“重复”声明的代码中)是函数会首先被提升,然后才是变量。在预解释的时候,如果名字已经声明过了,不需要从新的声明,但是需要重新的赋值;

我们先来看下两个简单的例子:

//例题1
 function a() {}
  var a
  console.log(typeof a)//'function'
//例题2
  var c = 1
  function c(c) {
    console.log(c)
    var c = 3
  }
  c(2)//Uncaught TypeError: c is not a function

当遇到存在函数声明和变量声明都会被提升的情况,函数声明优先级比较高,最后变量声明会被函数声明所覆盖,但是可以重新赋值,所以上个例子可以等价为

 function c(c) {
  console.log(c)
    var c = 3
  }
 c = 1
 c(2)

接下来我们看下两道比较复杂的题目:

//例题3
fn();
function fn(){console.log(1);};
fn();
var fn=10;
fn();
function fn(){console.log(2);};
fn();

1.一开始预解释,函数声明和赋值一起来,fn 就是function fn(){console.log(1);};遇到var fn=10;不会重新再声明,但是遇到function fn(){console.log(2);}就会从重新赋值,所以一开始fn()的值就是2

2.再执行fn();值不变还是2

3.fn重新赋值为10,所以运行fn()时报错,接下去的语句就没再执行。

//例题4
alert(a);
a();
var a=3;
function a(){
alert(10)
}
alert(a);
a=6;
a()

1.函数声明优先于变量声明,预解释时候,函数声明和赋值一起来,a就是function a(){alert(10)} ,后面遇到var a=3,也无需再重复声明,所以先弹出function a(){alert(10)}

2.a(),执行函数,然后弹出10

3.接着执行了var a=3; 所以alert(a)就是显示3

4.由于a不是一个函数了,所以往下在执行到a()的时候, 报错。


The above is the detailed content of What is JavaScript preinterpretation? JavaScript pre-interpretation parsing (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor