第 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也有自己的作用域。
会追问:「函数作用域和块作用域差在哪,举个例子?」——if 里 var 声明的变量出了 if 还能访问,let 就不能。 这是把老代码从 var改成 let 时最常见的破坏点。
In one line: four — global, function, block and module.
- Global — the outermost level. In a browser, a
vardeclared here lands onwindow. - Function — the territory of
varand the parameters, visible anywhere in the function body. - Block — any pair of
{}. It only bindslet/const/class;varignores 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.
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}
这道题的出处:Comes from: 课程里的这一节 →this lesson →用抽认卡过一遍Run a flashcard round