2023-02-09 23:38:45 +08:00

39 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: JavaScript进阶— 词法作用域
createTime: 2020/02/10 11:37:25
author: pengzhanbo
permalink: /article/fpcpgpod/
---
## 作用域
作用域是指 程序源代码中,定义变量的区域。
作用域规定了如何查找变量,也就是确定当前执行代码对变量的访问权限。
## 词法作用域
`JavaScript` 中,采用的是 词法作用域, 即静态作用域。
词法作用域规定了,函数的作用域是在 **函数定义的时候就确定** 了。
### 示例
```js
var a = 1
function foo() {
console.log(a)
}
function bar() {
var a = 2
foo()
}
bar()
```
这个示例的执行结果为 `1`
在这个例子中, 由于 函数`foo` 的作用域在 定义的时候就确定了,即使在 函数`bar` 中也有相同的变量名`a`的定义,
但是由于两个函数在定义时,作用域是相互独立的,函数`foo`在其作用域查找局部变量`a`,没有找到,
继续从它书写位置往上查找上一层的代码,所以输出的结果为 `1`