一、全局作用域(比如:window)
二、函数作用域(比如:function内声明的变量只能function内使用)
三、块级作用域(比如:if语句内声明的变量只能if内使用)
自由变量:一个变量如果在当前作用域没有定义,但被使用了,就向上级作用域一层一层寻找,直到找到位置,如果到全局作用域都没有找到,则报错xx is no defined,如下:
let a = 0;
function f1() {
let a1 = 100;
function f2() {
let a2 = 100;
function f3() {
let a3 = 200;
return a + a1 + a2 + a3;
}
return f3()
}
return f2()
}
f1() //返回400
闭包:所以的自由变量的查找是在函数定义的地方向上查找,不是在函数执行的地方查找,如下:
function create() {
let a = 100;
return function () {
console.log(a)
}
}
let b = create();
let a = 200;
b() //打印100
let a = 200;
function b() {
console.log(a)
}
function print() {
let a = 100;
b()
}
print() //打印200
this:取值是在函数执行的地方确定的,不是在函数定义的地方
1、作为普通函数
2、使用call apply bind
3、作为对象方法
4、在class方法中调用
5、箭头函数
function a() {
console.log(this)
}
a() //打印window
a.call({x: 10}) //打印{x: 10}
let b = a.bind({x: 20})
b() //打印{x: 20}
let people = {
name: '李四',
hello() {
//this为当前对象people
console.log(this)
},
wait() {
setTimeout(function () {
//由于this是在setTimeout方法中被执行,所以this为window
console.log(this)
})
},
wait1() {
setTimeout(() => {
//箭头函数this取上级作用域的值,this为当前对象people
console.log(this)
})
}
}
class people1{
constructor(name) {
this.name = name
}
hello() {
console.log(this)
}
}
let lishi = new people1('李四');
lishi.hello(); //打印this为lishi