JavaScript this指向总结

一 this指向

1.如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window

function fx (){
			console.log(this)
		}
		fx()

 2.如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。(this的指向完全取决于函数调用的位置

const obj = {
		uname:'张三',
		abc:	function fx() {
			console.log(this)
		}
	}

			obj.abc()

 

const arr = [function(){
				console.log(this)
			},1,2,3,4,5]
			arr[0]()

3. 箭头函数是没有this指向的它的this指向window,不会指回上一级

			const arr = [()=>{
					console.log(this)
				},1,2,3,4,5]
				arr[0]() 

 二 改变this指向的三种方法

   1.call() 方法

function fx (a,b) {
			console.log(this)
			return a + b
		}
	console.log(fx(1,1))

 此时 this 指向 window

使用call()方法改变this指向

const arr = [1,2,3,4,5,]
		function fx (a,b) {
			console.log(this)
			return a + b
		}
	console.log(fx.call(arr,1,3))

此时fx函数的this指向已经指向arr数组,并且使用call方法会自动触发函数,call()第一个参数是要指向谁,后边可以给函数传参数。

  2. apply()方法

	const arr = [1,2,3,4,5,]
		function fx (a,b) {
			console.log(this)
			return a + b
		}
	console.log(fx.apply(arr,[1,4]))

 此时fx函数的this指向已经指向arr数组,并且使用apply方法同样会自动触发函数,apply()第一个参数是要指向谁,后边可以给函数传参数和call方法不一样的是传参方式以数组形式传参。

3.bind()方法

		const arr = [1,2,3,4,5,]
		function fx (a,b) {
			console.log(this)
			return a + b
		}

	console.log(fx.bind(arr,1,7))	

使用bind方法时,和call方法很像但是不会立即触发函数而是返回一个新的函数。新的函数this指向就是改变后的指向。

		const arr = [1,2,3,4,5,]
		function fx (a,b) {
			console.log(this)
			return a + b
		}
	const newFx=	fx.bind(arr,1,7)
	console.log(newFx())	

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值