Home  >  Article  >  Web Front-end  >  JavaScript Topic One: Variable Promotion and Precompilation

JavaScript Topic One: Variable Promotion and Precompilation

coldplay.xixi
coldplay.xixiforward
2021-03-02 09:42:421802browse

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

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.

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); // 余光})();

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?

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); // ?
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 = '余光';

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(); // 函数执行

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

这段程序中:

  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;

上面代码中,变量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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete