var const let作用域

1.与第二个情况对比

1
2
3
4
5
6
7
8
9
10
11
const fn2 = () => {
var a1 = 88;
const fn1 = () => {
console.log('1~~~~', a1)
let a1 = 999;
}
fn1();
console.log('2~~~~',a1)
}
fn2();
// 第4行 VM270:4 Uncaught ReferenceError: a1 is not defined

总结:函数会从自身的活动对象开始,一层层向上寻找自己所需的变量,该函数在寻找a1时发现,自己的作用域里声明了let,它就不会再往上找,而let在声明之前是不可用的,所以就会报错

2.与第一个情况对比

1
2
3
4
5
6
7
8
9
10
11
12
const fn2 = () => {
var a1 = 88;
const fn1 = () => {
console.log('1~~~~', a1)
a1 = 999;
}
fn1();
console.log('2~~~~',a1)
}
fn2();
// 1~~~~ 88
// 2~~~~ 999

3.执行let a1的时候不会报错

1
2
3
4
5
6
7
8
9
10
const fn2 = () => {
var a1 = 88;
const fn1 = () => {
let a1 = 999;
}
fn1();
console.log('2~~~~',a1)
}
fn2();
// 2~~~~ 88

4.与1对比,执行let a1的时候报错

1
2
3
4
5
6
7
8
9
10
11
const fn2 = () => {
var a1 = 88;
const fn1 = () => {
var a1 = 777;
let a1 = 999;
}
fn1();
console.log('2~~~~',a1)
}
fn2();
// 第5行 Uncaught SyntaxError: Identifier 'a1' has already been
0%