Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

我使用了const为什么还有变量提升?

今天在看老代码的时候发现了一点疑问

// a === 1
const b = () => {
    a()
}
const a = () => {console.log(1)}
b()

读到上述代码发现const理论上不会被提升到代码顶部,为什么b函数内的a会被正确执行?

// a is not defined
const b = () => {
    a()
    const a = () => {console.log(1)}
}
b()

这段代码符合我的预期,在const之前就调用了a 。所以a不会执行

我查阅了一下资料。认为和es6的代码块作用域有关系,可是自己也没有琢磨明白。希望大佬给予指点


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

与提升无关。

第一种情况,虽然a定义在b后,但是b函数执行到a()时,a显然已经是一个函数,所以正常调用。
第二种情况,b函数执行到a(),a是啥还不知道,所以自然报错。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...