# 章序号/节序号/节/笔记序号 codecademy,scope # 概念阐释 - **block**: `{}`代码块中的一系列函数叫做代码块 - **global scope**: 全局作用域,在代码块外声明的变量,可在全局范围内使用 - **block scope**:代码块作用域,只能在代码块内使用,代码块外如果使用了代码块内的变量,会显示`ReferenceError`。 - 代码块中的代码块,例如function中的 if statement - **Scope Pollution 作用域污染**: 虽然了解什么是全局范围很重要,但最好不要在全局范围内定义变量。代码最好以**块**为单位储存,节省内存,查找错误也会更加方便。 # 举例子 ## global scope ```js const color = 'blue'; const returnSkyColor = () => {  return color; // blue }; console.log(returnSkyColor()); // color是在函数外定义的变量,但函数内也起作用,print blue ``` ## block scope ```js const logSkyColor = () => {   let color = 'blue';    console.log(color); // Prints "blue"}; logSkyColor(); // Prints "blue" console.log(color); // throws a ReferenceError 代码块外使用block scope变量 ``` ![](http://image.harryrou.wiki/2023-02-13-%E6%88%AA%E5%B1%8F2023-02-14%2007.48.04.png) ## block scope in if statement ```js const logSkyColor = () => {   const dusk = true;   let color = 'blue';   if (dusk) { let color = 'pink';     console.log(color); // if statement 下 Prints "pink"   }   console.log(color); // 函数的变量值 Prints "blue" }; console.log(color); // 快作用域外,throws a ReferenceError ``` # 类比、比较与对比 # 问题 用简洁方式写一个函数`logVisibleLightWaves`, 代码块内设定变量`lightWaves='Moonlight'` `region='The Arctic'`。 - print `lightWaves` 在if statement里,当`region==='The Arctic'`时`lightWaves='Northern Lights'` - print `lightWaves` 在 函数代码块中`lightWaves='Moonlight'` - 调用函数 **1.** Inside the function body of `logVisibleLightWaves()`, beneath the `region` variable and before the provided `console.log()` statement, create an `if` statement that checks if the `region` is the `'The Arctic'`. **2.** Inside the `if` block, define a new `let` variable `lightWaves` and set it equal to `'Northern Lights'`. **3.** Beneath the variable in the `if` block, use `console.log()` to log the value of the block variable inside the `if` block. Run your code and notice the output. Inside the `if` block `console.log(lightWaves)` logs the value `Northern Lights` to the console. Outside the `if` block, but still within the function, the same statement logs `Moonlight` to the console. # 问题答案 会得到两个答案,一个是if 代码块里面的变量值,一个是function里面的变量值。*且因为block scope,所以同一变量名可被宣称2次。* ```js const logVisibleLightWaves = () => { let lightWaves = 'Moonlight'; let region = 'The Arctic'; // Add if statement here: block scope只会影响block内的结果 if (region === 'The Arctic') { let lightWaves = 'Northern Lights'; console.log(lightWaves); } console.log(lightWaves); }; logVisibleLightWaves(); ``` # 备注(经验集/错误集) ## 经验集 - *return 不能出现在一组函数中两次* - *变量在block scope中可以多次用同一个变量名* ## 错误集 ## 参考资料