- today = "Friday";
- console.log(today);
- // Friday
-
- var today = "Monday!";
虽然declare的步骤在最后,但是today已经顺利打印出来,这是因为declare被hoist到顶部。
- var today; // hoisted declaration
- today = "Friday"; // the original line 1
- console.log(today); // Hello!
- today = "Monday"; // `var` is gone!
JSEngine事先将var举到顶部执行,并初始化值undefined.
接着查看function自举:
- today();
- // Friday!
-
- function today() {
- console.log("Friday");
- }
同样的原理在complie的步骤中,事先将所有的function都解析成AST,因此也就都hoist到了顶部。
继续考察function与variable二者的组合。
- today = "Friday";
- printToday();
- // Today is Friday.
-
- function printToday() {
- console.log(`Today is ${ today }!`);
- }
- var today;
实际的执行是先将function举起,再将var举起。
- function printToday() {
- console.log(`Today is ${ today }!`);
- }
- var today;
- today = "Friday";
- printToday();
- // Today is Friday.
二、重复declare的问题
考察下面的代码:
- let keepMoving = true;
- while (keepMoving) {
- let value = Math.random();
- if (value > 0.5) {
- keepMoving = false;
- }
- }
乍一看,似乎每次循环都会执行`let value = Math.random();`,但实际上只执行一次,执行一次后,declare 的部分将会从代码中移除。
三、变量初始化的问题TDZ问题
除了var之外,let也将举起,只是不会被初始化:
- var studentName = "Timy";
-
- {
- console.log(studentName);
- // ???
-
- let studentName = "Smith";
-
- console.log(studentName);
- // Smith
- }
第一个console不会输出 "Timy"而是会报错,说明let也被举起,只是没有被初始化。
解决此问题的方法就是将所有的let,const等全部都写到顶部。