Table of Contents
1.1 The opening I thought
1.2 This is actually the case
Still the above code:
3.1 函数会被首先提升,然后才是变量
3.2 函数字面量不会进行函数提升
4.1 变量提升是可以规避的
4.2 小结
Home Web Front-end JS Tutorial JavaScript Topic One: Variable Promotion and Precompilation

JavaScript Topic One: Variable Promotion and Precompilation

Mar 02, 2021 am 09:42 AM
javascript

JavaScript Topic One: Variable Promotion and Precompilation

Table of Contents

  • Foreword
  • 1. Interesting Phenomenon
  • 2. Pre-parsing of Js
  • 3. Priority between promotions
  • 4. ES6
  • Write at the end

(Related free learning recommendations: javascript video tutorial)

Preface

This article is the "JavaScript Specialized Advanced Series" 》The first article, the whole series may include, for example:

  • anti-shake throttling
  • flattening
  • deep and shallow copy
  • array Deduplication
  • Sort

and other classic special knowledge points. They are named Specialized Advanced because they have a high "appearance rate" on many occasions. In order to avoid becoming a google content searcher, the "JavaScript Specialized Advanced Series" was born ! ! !

JavaScript Topic One: Variable Promotion and Precompilation

1. Interesting phenomenon

According to common sense, JavaScript code must be executed from top to bottom. You need to output a string, and of course you need to declare a variable to save the string type in advance. If I can understand the profound truth, I read the following code.

1.1 The opening I thought
var str = '123';console.log(str); // 123
Copy after login

Let’s change the position of the code and look at it again:

console.log(str); // undefinedvar str = '123';
Copy after login

I seem to have found a pattern!!!

After I read the first two pieces of code and conducted "deep thinking", I seemed to have found the pattern, that is: in the function after the current code block, before variable declaration and initializationWhen using variables, you will not get the correct value.

JavaScript Topic One: Variable Promotion and Precompilation

1.2 This is actually the case

I came here with the above "conclusion"

var val = '余光';(function(){
    console.log(val); // 余光})();
Copy after login

As expected! , after variable declaration and initialization Jesus can’t stop me from getting the value of val, I said it! ! !

When I saw the following piece of code, I was already shaken. This matter must be strange.

var val = '余光';(function(){
    console.log(val); // undefined
    var val = '测试';})();
Copy after login

Ps: If you have questions about executing functions immediately, you might as well take a look at "JavaScript's In-depth Understanding of Immediately Invoked Function Expressions (IIFE)"~

This...I'm scared, what is it? What causes this phenomenon to occur? How does Js handle it?

JavaScript Topic One: Variable Promotion and Precompilation

2. Js pre-parsing

In the current scope, no matter where the variable is declared, it will be done behind the scenes An invisible movement.

Note: Only statements are "moved" . That is, declaration and assignment are passively separated at some point. And this invisible movement is actually the parsing of Js during the compilation phase.

Let’s take a look at a classic example from "Do you know JS":

name = '余光'; // 未添加关键字(未声明),name为全局变量,,即window.name = '余光'var name; // 再次声明name,此时name未进行初始化,它的值是undefined吗?console.log(name); // ?
Copy after login
The result is that the "afterglow" is successfully printed, so that

invisible movement It happens during Js pre-parsing (compilation).

2.1 Core: Pre-parsing
In order to understand this core issue, we need to review that the engine will first compile the JavaScript code before interpreting it. Part of the compilation phase is to find all the declarations and associate them with the appropriate scope. Interested friends can read the two articles "Variable Objects in JavaScript" and "From Scope to Scope Chain" ~

Therefore, when something like this happens, including

variables## All declarations including # and functions will be processed first before any code is executed. When you see var a = 2;, you might think that this is a statement. But JavaScript actually sees this as two declarations: var a; and a = 2;.

The first definition statement is made during the compilation phase.
  • The second assignment statement will be left in place waiting for the execution phase.
  • That is, the code is written like this:
// 我们看到的代码:var name = '余光';
Copy after login

But Js will parse it into:

// 声明(Declaration)var name; // 声明但未初始化,所以分配 undefined// 初始化(Initialization)name = '余光'; // 初始化(赋值)
Copy after login

So a piece of code in this summary should be analyzed like this:

var name; // 声明name提到作用域顶部,并被分配了一个undefinedname = '余光'; // 进行初始化操作console.log(name); // '余光'
Copy after login

2.2 Note: Only the declaration is promoted

Only the declaration will be promoted, and assignment and other code logic will not take effect until the execution of the code position

. So there will be the following problem:

foo();function foo(){
    console.log(name); // undefined
    var name = '余光';}
Copy after login
Copy after login
The function is promoted and can naturally be executed normally, but the variable is only declared to be promoted.

2.3 Each scope will be promoted

Still the above code:
foo();function foo(){
    console.log(name); // undefined
    var name = '余光';}
Copy after login
Copy after login

Actually, it looks like this when compiling:

function foo(){
    var name; // 声明
    console.log(name); // undefined
    name = '余光'; // 初始化}foo(); // 函数执行
Copy after login

JavaScript Topic One: Variable Promotion and Precompilation

3. Priority between promotions

Now that we know that

variables

and functions will be promoted , how do they judge priorities? <h5 id="函数会被首先提升-然后才是变量">3.1 函数会被首先提升,然后才是变量</h5> <p>我们分析下面的代码:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">foo();var foo; // 1function foo(){     console.log('余光');}foo = function(){     console.log('小李');}</pre><div class="contentsignin">Copy after login</div></div> <p>本着函数优先提升的原则,他会被解析成这样:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">function foo(){     console.log('余光');}foo(); // 余光foo = function(){     console.log('小李');}</pre><div class="contentsignin">Copy after login</div></div> <p>注意,<code>var foo 因为是一个重复声明,且优先级低于函数声明所以它被忽略掉了。

3.2 函数字面量不会进行函数提升

最直观的例子,就是在函数字面量前调用该函数:

foo();var foo = function(){
    console.log(1);}// TypeError: foo is not a function
Copy after login

这段程序中:

  1. 变量标识符foo被提升并分配给所在作用域(在这里是全局作用域),因此在执行foo()时不会导致ReferenceError(),而是会提示你 foo is not a function
  2. 然后就是执行foo,foo此时并没有赋值(注意变量被提升了)。由于对undefined值进行函数调用而导致非法操作,因此抛出TypeError异常。

四、ES6和小结

ES6新增了两个命令letconst,用来声明变量,有关它们完整的概念我会在《ES6基础系列》中总结,提起它们,是因为变量提升在它们身上不会存在

4.1 变量提升是可以规避的

let命令改变了语法行为,它所声明的变量一定要在声明后使用,否则报错。

// var 的情况console.log(foo); // 输出undefinedvar foo = 2;// let 的情况console.log(bar); // 报错ReferenceErrorlet bar = 2;
Copy after login

上面代码中,变量foo用var命令声明,会发生变量提升,即脚本开始运行时,变量foo已经存在了,但是没有值,所以会输出undefined。变量bar用let命令声明,不会发生变量提升。这表示在声明它之前,变量bar是不存在的,这时如果用到它,就会抛出一个错误。

在变量提升上,const和let一样,只在声明所在的块级作用域内有效,也不会变量提升

4.2 小结
  1. 变量提升:函数声明和变量声明总是会被解释器悄悄地被"提升"到方法体的最顶部,但变量的初始化不会提升;
  2. 函数提升:函数声明可以被看作是函数的整体被提升到了代码的顶部,但函数字面量表达式并不会引发函数提升;
  3. 函数提升优先与变量提升;
  4. let和const可以有效的规避变量提升

最后提炼一下:JavaScript引擎并不总是按照代码的顺序来进行解析。在编译阶段,无论作用域中的声明出现在什么地方,都将在代码本身被执行前首先进行处理,这个过程被称为提升。声明本身会被提升,而包括函数表达式的赋值在内的赋值操作并不会提升。

相关免费学习推荐:javascript(视频)

The above is the detailed content of JavaScript Topic One: Variable Promotion and Precompilation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles