Skip to content

Commit

Permalink
update scope md
Browse files Browse the repository at this point in the history
  • Loading branch information
Xicheng Guo committed May 23, 2024
1 parent 0dd3f32 commit 667dd09
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/.vitepress/sidebar.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
link: /javascript/introduction/core-implementation
- text: JavaScript 调用栈
link: /javascript/introduction/call-stack
- text: JavaScript 作用域
link: /javascript/introduction/scope
- text: ECMAScript
items:
- text: ES 的版本
Expand Down
1 change: 1 addition & 0 deletions src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import MarkMap from './MarkMap.vue';
- [JavaScript 发展历程](javascript/introduction/history-of-javascript)
- [JavaScript 核心实现](javascript/introduction/core-implementation)
- [JavaScript 调用栈](javascript/introduction/call-stack)
- [JavaScript 作用域](javascript/introduction/scope)
- ECMAScript
- [ES 的版本](javascript/ecma-script/es-version)
- [变量声明](javascript/ecma-script/variable-declaration)
Expand Down
69 changes: 69 additions & 0 deletions src/javascript/introduction/scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# JavaScript 作用域

## 什么是作用域

作用域是指程序中变量和函数可被访问的区域。

JavaScript 中的作用域分为:全局作用域、函数作用域和块级作用域。

::: details 什么是词法作用域

词法作用域是指代码中变量和函数的作用域是在代码编写时就确定的,而不是在代码执行时确定的。

JavaScript 遵循词法作用域。

:::

### 全局作用域

全局作用域是指在代码中任何地方都能访问的变量和函数。

```javascript
var a = 1;
function foo() {
console.log(a);
}
foo(); // 1
```

### 函数作用域

函数作用域是指在函数内部定义的变量和函数只能在函数内部访问。

```javascript
function foo() {
var a = 1;
console.log(a);
}
foo(); // 1
console.log(a); // ReferenceError: a is not defined
```

### 块级作用域

块级作用域是指在代码块内部定义的变量和函数只能在代码块内部访问。

```javascript
if (true) {
let a = 1;
console.log(a);
}
console.log(a); // ReferenceError: a is not defined
```

## 作用域链

作用域链是指在代码中查找变量和函数的过程。

```javascript
var a = 1;
function foo() {
var b = 2;
function bar() {
var c = 3;
console.log(a, b, c);
}
bar(); // 1 2 3
}
foo();
```

0 comments on commit 667dd09

Please sign in to comment.