DrillLab
第 30 / 105 道30 / 105 · #295

作用域有哪几种

What are the different type of scopes

先自己答,再往下看Answer it yourself first

一句话:四种 —— 全局、函数、块、模块。

  • 全局—— 最外层。浏览器里var 声明的会挂到 window
  • 函数—— var和函数参数的地盘,整个函数体内都可见
  • —— 任意一对 {}只对 let / const/ class 有效var 无视它。
  • 模块—— 每个 ES 模块文件自己一个作用域, 顶层声明不会污染全局

顺带一个常被忽略的:catch (e)e也有自己的作用域。

会追问:「函数作用域和块作用域差在哪,举个例子?」——ifvar 声明的变量出了 if 还能访问let 就不能。 这是把老代码从 var改成 let 时最常见的破坏点。

In one line: four — global, function, block and module.

  • Global — the outermost level. In a browser, a var declared here lands on window.
  • Function — the territory of var and the parameters, visible anywhere in the function body.
  • Block — any pair of {}. It only binds let / const / class; var ignores it completely.
  • Module — every ES module file gets a scope of its own, so top-level declarations do not pollute the global scope.

One that people forget: the e in catch (e) has its own scope too.

Follow-up: “Give me an example of function scope against block scope” — a var declared inside an if is still readable after the if; a let is not. That is the thing you break most often when converting old var code to let.

JavaScript函数作用域 vs 块作用域Function scope vs block scope示意Illustrative
1function f() {
2 if (true) {
3 var a = 1; // 函数作用域
4 let b = 2; // 块作用域
5 }
6 console.log(a); // 1 ✓ var 无视 {}
7 console.log(b); // ReferenceError
8}
1function f() {
2 if (true) {
3 var a = 1; // function scope
4 let b = 2; // block scope
5 }
6 console.log(a); // 1 ✓ var ignores {}
7 console.log(b); // ReferenceError
8}