Home>Article>Web Front-end> JavaScript Topic One: Variable Promotion and Precompilation
Table of Contents
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:
and other classic special knowledge points. They are namedSpecialized Advancedbecause they have a high "appearance rate" on many occasions. In order to avoid becoming agoogle 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 avariable
to save the string type in advance. If I can understand the profound truth, I read the following code.
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.
I came here with the above "conclusion"
var val = '余光';(function(){ console.log(val); // 余光})();
As expected! , aftervariable declaration and initializationJesus 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 parsingof 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 movementIt 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, includingvariables## All declarations including # andfunctions
will be processed first before any code is executed. When you seevar a = 2
;, you might think that this is a statement. But JavaScript actually sees this as two declarations: var a; and a = 2;.
// 我们看到的代码: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
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(); // 函数执行3. Priority between promotions
Now that we know that
variablesand 我们分析下面的代码: 本着函数优先提升的原则,他会被解析成这样: 注意, 最直观的例子,就是在函数字面量前调用该函数: 这段程序中: 四、ES6和小结 ES6新增了两个命令 let命令改变了语法行为,它所声明的变量一定要在声明后使用,否则报错。 上面代码中,变量foo用var命令声明,会发生变量提升,即脚本开始运行时,变量foo已经存在了,但是没有值,所以会输出undefined。变量bar用let命令声明,不会发生变量提升。这表示在声明它之前,变量bar是不存在的,这时如果用到它,就会抛出一个错误。 在变量提升上,const和let一样,只在声明所在的块级作用域内有效,也不会变量提升 最后提炼一下: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!functions
will be promoted , how do they judge priorities?3.1 函数会被首先提升,然后才是变量
foo();var foo; // 1function foo(){ console.log('余光');}foo = function(){ console.log('小李');}
function foo(){ console.log('余光');}foo(); // 余光foo = function(){ console.log('小李');}
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
。let
和const
,用来声明变量,有关它们完整的概念我会在《ES6基础系列》中总结,提起它们,是因为变量提升在它们身上不会存在。4.1 变量提升是可以规避的
// var 的情况console.log(foo); // 输出undefinedvar foo = 2;// let 的情况console.log(bar); // 报错ReferenceErrorlet bar = 2;
4.2 小结