闭包
什么是闭包,简单来说, 函数里面返回一个函数,而这个函数就是函数内外联系的一座桥梁
例如 在函数1里面返回一个函数2, 函数2可以访问函数1里面的变量
//在闭包函数里面定义了一个变量和一个函数
function closure() {
let a = 10
function test1(){
console.log(a)
}
return test1
}
//console.log(a)//报错,全局作用域里面不能访问局部作用域里面的变量
//但此时又想拿到 closure 里面的 a 就要通过 test1 方法
closure()()//打印结果 10
闭包中的this的指向是如何的?
原则: 谁调用指向谁
- 闭包里面返回一个函数
function closure() {
let a = 10
function test1(){
console.log(a)//10
console.log(this)//Window
}
return test1
}
//console.log(a)//报错,全局作用域里面不能访问局部作用域里面的变量
//但此时又想拿到 closure 里面的 a 就要通过 test1 方法
closure()()//打印结果 10
//等价于
let test = closure()//此时: test = test1这个方法
test()//等价于 window.test()
//this 指向调用者: 所以 this 就为 Window
- 闭包里面返回一个对象
function closure() {
let a = 10
function test1(){
console.log(a)//10
console.log(this)//{test1: ƒ}
}
return {test1}
}
//console.log(a)//报错,全局作用域里面不能访问局部作用域里面的变量
//但此时又想拿到 closure 里面的 a 就要通过 test1 方法
closure().test1()
//等价于
let test = closure()//此时: test = {test1}这个对象
test.test1()
//this 指向调用者: 所以 this 就为 closure() 执行后返回的对象
总结 : this 指向调用者,也可以理解为指向调用的上层 对象(因为 this 是可以指向 dom节点对象 window对象 还有对象 总的来说都是指向对象)
例如:
window.test()上层对象是 window,所以指向window
obj.test()上层对象是 obj,所以指向obj
个人浅见,如有错误,欢迎指出