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 ! ! !
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
Let’s change the position of the code and look at it again:
console.log(str); // undefinedvar str = '123';
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.
1.2 This is actually the case
I came here with the above "conclusion"
var val = '余光';(function(){ console.log(val); // 余光})();
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 = '测试';})();
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?
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.
name = '余光'; // 未添加关键字(未声明),name为全局变量,,即window.name = '余光'var name; // 再次声明name,此时name未进行初始化,它的值是undefined吗?console.log(name); // ?
invisible movement It happens during Js pre-parsing (compilation).
2.1 Core: Pre-parsingIn 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, includingvariables## 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 second assignment statement will be left in place waiting for the execution phase.
- That is, the code is written like this:
// 我们看到的代码:var name = '余光';
But Js will parse it into:
// 声明(Declaration)var name; // 声明但未初始化,所以分配 undefined// 初始化(Initialization)name = '余光'; // 初始化(赋值)
So a piece of code in this summary should be analyzed like this:
var name; // 声明name提到作用域顶部,并被分配了一个undefinedname = '余光'; // 进行初始化操作console.log(name); // '余光'
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 = '余光';}
2.3 Each scope will be promoted
Still the above code:
foo();function foo(){ console.log(name); // undefined var name = '余光';}
Actually, it looks like this when compiling:
function foo(){ var name; // 声明 console.log(name); // undefined name = '余光'; // 初始化}foo(); // 函数执行
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
这段程序中:
- 变量标识符
foo
被提升并分配给所在作用域(在这里是全局作用域),因此在执行foo()时不会导致ReferenceError(),而是会提示你foo is not a function
。 - 然后就是执行foo,foo此时并没有赋值(注意变量被提升了)。由于对undefined值进行函数调用而导致非法操作,因此抛出TypeError异常。
四、ES6和小结
ES6新增了两个命令let
和const
,用来声明变量,有关它们完整的概念我会在《ES6基础系列》中总结,提起它们,是因为变量提升在它们身上不会存在。
4.1 变量提升是可以规避的
let命令改变了语法行为,它所声明的变量一定要在声明后使用,否则报错。
// var 的情况console.log(foo); // 输出undefinedvar foo = 2;// let 的情况console.log(bar); // 报错ReferenceErrorlet bar = 2;
上面代码中,变量foo用var命令声明,会发生变量提升,即脚本开始运行时,变量foo已经存在了,但是没有值,所以会输出undefined。变量bar用let命令声明,不会发生变量提升。这表示在声明它之前,变量bar是不存在的,这时如果用到它,就会抛出一个错误。
在变量提升上,const和let一样,只在声明所在的块级作用域内有效,也不会变量提升
4.2 小结
- 变量提升:函数声明和变量声明总是会被解释器悄悄地被"提升"到方法体的最顶部,但变量的初始化不会提升;
- 函数提升:函数声明可以被看作是函数的整体被提升到了代码的顶部,但函数字面量表达式并不会引发函数提升;
- 函数提升优先与变量提升;
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 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

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 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 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

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).

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 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
