版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/pangji0417/article/details/78320072
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之前有暂时性死区。