3. 解释 Hoisting

在我们之前提到的Execution Context,都会执行一个被称为"Hoisting的步骤"。

https://ithelp.ithome.com.tw/upload/images/20210904/20129476fUM5tkzyKg.png

https://ithelp.ithome.com.tw/upload/images/20210904/20129476K2YPaIAqse.png

而今天就要来复习hoisting ~

定义


  • initialize var & function

JavaScript Hoisting refers to the process whereby the interpreter allocates memory for variable and function declarations prior to execution of the code.

Declarations that are made using var are initialized with a default value of undefined. Declarations made using let and const are not initialized as part of hoisting.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

而Hoisting执行的行为是: 电脑会先分配记忆体给var和function Declaration。

[var] vs. [let & const]


所以我们要来了解这个行为的影响,
首先,看看let,const和var的例子:

console.log(x); // ReferenceError: x is not defined

let x = 100;  
console.log(x); // ReferenceError: x is not defined

const x = 100;  

如果是用let或const宣告的变数,不会被提前分配记忆体,
就不会提升initialize这个行为,

因此,如果在宣告变数前就使用变数,那麽就会弹出ReferenceError,告诉你变数还未被定义。

console.log(x); // output: undefined

var x = 100;  

然而被用var宣告的变数,这里的console会告诉你undefined

也就是说,对浏览器而言,这个变数已经被初始化过了。
(浏览器知道这个变数存在,只是尚未被赋值。)

[Function Declaration] vs. [Function Expression]


使用 Function Declaration 也会被hoisting:

functionDeclaration();  // output: 100

function functionDeclaration(){
    console.log(100);
}

要注意的是,执行Function Expression就不会被进行hoisting:

functionExpression();  // ReferenceError: functionExpression is not defined

const functionExpression = () => {
    console.log(100);
}

而上面是最粗浅的解释,如果想要深入理解很推荐这篇文章:
我知道你懂 hoisting,可是你了解到多深?

【如果内文有误还请不吝指教>< 也谢谢阅览至此的各位:D】

-----正文结束-----

今天比较忙所以打的比较简单,但之前有看过整理的很好的文章,就也放进来了。


<<:  Day4 : Hello World 程序再解析

>>:  为什麽87% 的资料科学专案没办法产品化? | MLOps落地指南 - 技术篇

Day 24 (Js)

1.window.alert vs. window.confirm (1)window.alert:...

[Day-17] 二维阵列

今天要来延续上次练习的阵列 这次要练习的阵列跟上次的有点不一样 那就是一维阵列的进阶版「二维阵列」 ...

Day 16-隔离框架 (isolation Framework) - NSubstitute 基本介绍 (核心技术-8)

NSubstitute 基本介绍与安装 NSubstitute(简称 NSub)是一套友善的 .NE...

Day02 工欲善其事必先利其器

VS Code Extension外挂套件 在建立React应用程序之前,建议可先安装VS Code...

D1- 谁适合使用 Google Apps Script (GAS)呀?

Google Sheet 甚至可以帮你 Host 一个网站、能跟 slack 、 Biance 与...