闭包
1. 如何产生闭包(closure)
上图代码:
// 函数作为返回值
function create() {
const a = 100
return function () {
console.log(a)
}
}
const fn = create()
const a = 200
fn() // 100
// 函数作为参数被传递
function print(fn) {
const a = 200
fn()
}
const a = 100
function fn() {
console.log(a)
}
print(fn) // 100
所有的自由变量的查找,是在函数定义的地方,向上级作用域查找
不是在执行的地方!!!
2. this
5大调用场景:
普通函数、
对象方法、
call apply bind
class
箭头函数
注意:
this取什么值,是在执行时确认的,定义时无法确认
全局下,普通函数fn1执行,相当于window执行了fn1函数,所以this是window
call apply bind可以修改this,
function fn1(this={
x:100}){
fn1,call({
x:100}) ==> console.log(this)
}
bind也可以修改,但是多了一步执行。