JavaScript 預編譯


Posted by hata0833 on 2022-08-25

今天做筆試的時候遇到了一題

console.log(a)
var a = 0
a = function() {console.log('111')}
function a() {console.log('222')}

最終輸出是 function a() {console.log('222')}
Imgur
晚上在複習JS基礎的時候看到了變量提升,在阮一峰的文檔裡是這樣寫的
Imgur

https://wangdoc.com/javascript/basic/grammar.html

對於一開始那道題,進行過預編譯後是這樣的
變量聲明會被提升(即表達式前面,var a 的部分)
function的聲明也會被提升,整行代碼被提到了最前面,因此console.log(a)時出現的不是undefined,而是預編譯後被提升到頭部的function a()

var a
function a() {console.log('222')}
console.log(a)
a = 0
a = function() {console.log('111')}

#javascript







Related Posts

The Mix manifest does not exist. (View: C:\laragon\www\fc\resources\views\layouts\_head.blade.php)

The Mix manifest does not exist. (View: C:\laragon\www\fc\resources\views\layouts\_head.blade.php)

筆記、SSH

筆記、SSH

Inheritance

Inheritance


Comments