它们在三个方面不同:scope、hoisting behavior 和 reassignment。
js
() {
() {
a = ;
b = ;
c = ;
}
.(a);
.(b);
}
var 是 function-scoped,被提升并初始化为 undefined,可以重新声明。这会导致意外的泄漏 — 避免使用。let 是 block-scoped({ }),可以重新赋值,并在其声明行之前存在于 temporal dead zone 中(提前访问会抛出错误)。const 是 block-scoped 并且 不能重新赋值 — 但注意绑定是常量,而不是值:const user = { name: "Ann" };
user.name = "Bob"; // ✅ allowed — mutating the object, not reassigning
user = {}; // ❌ TypeError — can't rebind `user`
默认使用 const;仅在必须重新赋值时切换到 let;在新代码中永远不要使用 var。这使意图明确("这不会改变"),并避免 var 带来的作用域泄漏和变量提升混淆。