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); // ?The result is that the "afterglow" is successfully printed, so that
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 = '余光';}
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 = '余光';}
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>
<pre class="brush:php;toolbar:false">foo();var foo; // 1function foo(){
console.log('余光');}foo = function(){
console.log('小李');}</pre>
<p>本着函数优先提升的原则,他会被解析成这样:</p>
<pre class="brush:php;toolbar:false">function foo(){
console.log('余光');}foo(); // 余光foo = function(){
console.log('小李');}</pre>
<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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
