JavaScript 之 var 和 let
阿新 • • 發佈:2018-11-11
1.變數提升的機制
var tmp = new Date();
function f() {
let tmp = 'a';
console.log(tmp);
let tmp = 'helloworld';
console.log(tmp);
}
f();
報錯,因為重複宣告tmp,改為:
無錯誤var tmp = new Date(); function f() { let tmp = 'a'; console.log(tmp); tmp = 'helloworld'; console.log(tmp); } f();
var tmp = new Date();
function f() {
var tmp = 'a';
console.log(tmp);
var tmp = 'helloworld';
console.log(tmp);
}
f();
無錯誤。因為var有變數提升機制,上段程式碼相當於以下程式碼:
var tmp = undefined; tmp = new Date(); function f() { var tmp = undefined; tmp = 'a'; console.log(tmp); tmp = 'helloworld'; console.log(tmp); } f();
2.let的暫時性死區TDZ
var tmp = new Date();
function f() {// TDZ start
console.log(tmp);
let tmp = 'helloworld';// TDZ end
console.log(tmp);
}
f();
報錯,JavaScript是函式級作用域,在let宣告tmp之前有暫時性死區。