this 指向3 闭包中的 this 指向

闭包

什么是闭包,简单来说, 函数里面返回一个函数,而这个函数就是函数内外联系的一座桥梁
例如 在函数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的指向是如何的?

原则: 谁调用指向谁

  1. 闭包里面返回一个函数
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
  1. 闭包里面返回一个对象
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

个人浅见,如有错误,欢迎指出

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值