说说对js中变量作用域的理解
# 是什么
作用域:变量能访问的区域集合
- 类型
- 块级作用域
- 函数作用域
- 全局作用域
# 词法作用域
又称静态作用域:变量创建的时候就确定好了,而不是执行的时候
var a = 2;
function foo() {
console.log(a);
}
function bar() {
var a = 3;
foo();
}
bar();
# 作用域链
在使用变量时,js 引擎会在当前作用域去寻找该变量,如果没有找到,会去它的上层寻找,以此类型,直到顶层全局作用域,这个查找链路称为作用域链
var sex = "男";
function person() {
var name = "张三";
function student() {
var age = 18;
console.log(name); // 张三
console.log(sex); // 男
}
student();
console.log(age); // Uncaught ReferenceError: age is not defined
}
person();
上次更新: 2021/12/19, 18:05:42