## 作用域(Scope)

``````function fn() {
var inVariable = "inner variable";
console.log(inVariable); // inner variable
}

fn();
console.log(inVariable); // Uncaught ReferenceError: inVariable is not defined
``````

• 全局作用域 — 变量可以随处访问
• 函数作用域— 变量可以在定义它们的函数的边界内访问
• 块级作用域—变量可以在定义它们的块中访问，块由 { 和 } 分隔

## 全局作用域和函数作用域

``````const global = 'global scoped'

function fn() {
const global = 'function scoped';
console.log(global); // function scoped
}

fn();
console.log(global); // global scoped
``````

``````const global = 'global scoped'
const anotherGlobal = 'also global scoped'

function fn() {
const global = 'function scoped'
console.log(global) // function scoped
const scoped = 'also function scoped'

function inner() {
console.log(scoped); // also function scoped
console.log(anotherGlobal) // also global scoped
}

inner();
}

console.log(global); // global scoped
console.log(anotherGlobal); // also global scoped

fn();
inner(); // Uncaught ReferenceError: inner is not defined
``````

``````function fn() {
variable = "undeclared variable";
var inVariable = "inner variable";
}

fn();
console.log(variable); // undeclared variable
console.log(inVariable); // Uncaught ReferenceError: inVariable is not defined
``````

``````if (true) {
// 'if' 条件语句块不会创建一个新的作用域
var name = 'miqilin'; // name 依然在全局作用域中
}

console.log(name); // miqilin
``````

JS 的初学者经常需要花点时间才能习惯变量提升，而如果不理解这种特有行为，就可能导致bug出现 。正因为如此， ES6 引入了块级作用域，让变量的生命周期更加可控。

## 块级作用域

1. 在一个函数内部
2. 在一个代码块（由一对花括号包裹）内部

let 声明的语法与 var 的语法一致。你基本上可以用 let 来代替 var 进行变量声明，但会将变量的作用域限制在当前代码块中。块级作用域有以下几个特点：

• 声明变量不会提升到代码块顶部

let/const创建的变量不会像使用var声明的变量那样被提升到顶部，因此你需要手动将 let/const 声明放置到顶部，以便让变量在整个代码块内部可用。比如：

``````cosole.log(name); // Uncaught ReferenceError: cosole is not defined
const name = "miqilin";
``````

• 禁止重复声明

``````var count = 10;
let count = 20; // Uncaught SyntaxError: Identifier 'count' has already been declared
``````

``````var count = 10;
// 不会抛出错误
if (condition) {
let count = 20;
// 其他代码
}
``````
• 循环中的绑定块作用域的妙用

``````for (let i = 0; i < 10; i++) {
// ...
}
console.log(i);
// ReferenceError: i is not defined
``````

``````var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a(); // 10
``````

``````var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a(); // 6
``````

``````for (let i = 0; i < 5; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc
// abc
// abc
``````

## 作用域链(Scope Chain)

``````function a() {

function b() {
console.log(myVar);
}

var myVar = 2;
b();
}

var myVar = 1;
a(); // 2
b(); // Uncaught ReferenceError: b is not defined
``````

1. 执行a()会得到2的结果：之所以会有这样的结果，是因为当我们执行function a里面的function b时，因为在function b里面它找不到myVar这个变量，因此它开始往它的外层去搜寻，而这时候它的父级作用域是function a，在function a里面它便找到了myVar = 2，因此它就不再往外部环境 (myVar = 1)去找了，直接返回了2这样的结果。

2.b()会得到b is not defined的结果：之所以b会是not defined（记得是not defined不是undefined哦！)，是因为这时候在最外层的全局上下文（global execution context）中，找不到function b。

``````function a() {

function b() {
console.log(myVar);
}

//var myVar = 2;
b();
}

var myVar = 1;
a(); // 1
``````

``````function a() {

function b() {
console.log(myVar);
}

//var myVar = 2;
b();
}

//var myVar = 1;
a(); // Uncaught ReferenceError: myVar is not defined
``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.8324466,"math_prob":0.97537917,"size":5539,"snap":"2020-10-2020-16","text_gpt3_token_len":3640,"char_repetition_ratio":0.15284553,"word_repetition_ratio":0.21062993,"special_character_ratio":0.23217188,"punctuation_ratio":0.1377841,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9638263,"pos_list":[0,1,2],"im_url_duplicate_count":[null,3,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-02-20T02:44:55Z\",\"WARC-Record-ID\":\"<urn:uuid:879c8225-3152-4541-bed8-47c6afd239fe>\",\"Content-Length\":\"119081\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7522b8e5-17ce-4965-9717-37ccf6b261c7>\",\"WARC-Concurrent-To\":\"<urn:uuid:53b8a854-ce72-4b04-81c2-366735e83f24>\",\"WARC-IP-Address\":\"104.121.94.195\",\"WARC-Target-URI\":\"https://zhuanlan.zhihu.com/p/69910449\",\"WARC-Payload-Digest\":\"sha1:I2KIN6M4TROUCKTHAFB5HQLAMXJLGVZ3\",\"WARC-Block-Digest\":\"sha1:PAMQ2NVE5BE2LKJDQBL5YJ3SWLZWS4ML\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-10/CC-MAIN-2020-10_segments_1581875144498.68_warc_CC-MAIN-20200220005045-20200220035045-00176.warc.gz\"}"}