预处理

提前处理 var、 const、 let、 function 声明、 class 声明 。

var

如果 var 出现在 if 语句块中

会提升到所在作用域的头部

console.log(a); // undefined
var a = 1;

如果 var 出现在 with 中

不定,不推荐使用 with

var a = 1;
function test() {
  var o = { a: 2 };
  with (o) {
    var a = 3;
  }
  console.log(o.a); // 3
  console.log(a); //undefined
}
test();

function 声明

会提升到所在作用域的头部并赋值

console.log(a); // function a(){}
function a() {}

如果 function 声明出现在 if 语句块中

会声明但不赋值

console.log(a); // undefined
if (true) {
  function a() {}
}

const、let、class

声明前都有暂时性死区,声明前不允许使用变量,但不代表没有被预处理

console.log(a) // SyntaxError
let a = 1
console.log(b) // SyntaxError
const b = 2
console.log(C) // SyntaxError
calss C{}
posted @ 2025-11-17 18:24  jinzhepro  阅读(6)  评论(0)    收藏  举报