不允许重复定义
在ES6中基于let/const等方式创建变量或函数,不存在变量提升机制
=>切断了全局变量和window属性的映射机制
=>在相同的作用域,基于let不能声明相同名字的变量(不管用什么方式再当前作用域下声明了变量,再次使用let创建都会报错)
虽然没有变量提升机制,但是在当前作用域代码自上而下执行之前,浏览器会做一个重复性检测(语法检测):自上而下查找当前域下所有变量,一旦发现有重复的,直接抛出异常,代码也不会再执行了(虽然没有把变量提前声明定义,但是浏览器已经己住了,当前作用域下有哪些变量)
console.log(a)//=>a is not defined
let a=12;
console.log(window.a)//=>undefined
console.log(a)//=>12
b=12
console.log(b)//=>12
a=12;//=>a is not defined
console.log(a)
let a=13;
console.log(a)
let a = 12;
console.log(a)
let a = 13;//=>报错identifier 'a' has been declared
console.log(a)
let a = 10,
b=10;
let fn=function(){
console.log(a,b)//=>uncaught referenceError,Cannot access 'a' before initialization
let a=b=20;
console.log(a,b)
}
fn();
console.log(a,b)
let a = 10,
b=10;
let fn=function(){
let a=b=20;
console.log(a,b)//=>20,20
}
fn();
console.log(a,b)//=>10,20
let fn=()=>{
};
不存在变量提升
console.log(a)//=>uncaught referenceError: a is not defined
let a;
console.log(typeof a)//=>uncaught referenceError: a is not defined
let a;
暂时性死区
var a=12;
if(ture){
console.log(a);//=>uncaught referenceError: a is not defined
let a=13;//=>基于let创建变量,会把大部分{}当作一个私有得块级作用域(类似于函数得私有作用域),在这里也是重新检测语法规范,看一下是否是基于新语法创建得变量,如果是按照信誉发规范来解析
}
console.log(a)//=>uncaught referenceError: a is not defined
console.log(typeof a)//=>undefined在原有浏览器渲染机制下,基于typeof等逻辑运算符检测一个未被声明过得变量,不会报错,返回undefined
如果当前变量是基于ES6语法处理,在没有声明这个变量的时候,使用typeof检测会直接报错,不会是undefined,解决了原有JS暂时性死区问题