zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript:更改this指向——call,apply,bind的用法

JavaScript 用法 this 更改 call bind apply 指向
2023-09-11 14:22:28 时间

在上篇文章中已经记录了,在JS中关于this关键字的指向问题,那么本文就来记录一下,如何去更改this指向,以及ES6的箭头函数!

上篇文章:JavaScript:一文搞懂this关键字指向_Jay丶千珏的博客-CSDN博客

目录

提出问题

1. call,apply,bind——无额外参数传递

        1.1 call无额外参数传递用法

        1.2 apply无额外参数传递用法

        1.3 bind无额外参数传递用法

        小结

2. call,apply,bind——额外参数传递

       2.1 call额外参数传递用法

       2.2 apply额外参数传递用法

        2.3 bind无额外参数传递用法

        小结

3. ES6箭头函数

4. 题外话


提出问题

首先,先来看一个问题。

        const name = '李青';
        const r = '神龙摆尾';
        const obj = {
            name: '盲僧',
            q: '天音波-回音击',
            myFun() {
                console.log(this)
                console.log('name===>', this.name)
                console.log('q===>', this.q)
                console.log('r===>', this.r)
            }
        }
        obj.myFun()

 

 这个输出,没有什么疑问吧,this指向当前所处的对象obj,输出并没有什么问题。现在来提出一个问题!

在不改变obj的情况下,我想让name输出 李青,q输出 天音波-回音击, r输出 神龙摆尾,怎么办?

那么就到了更改this指向的时间!call,apply,bind三个方法,传递的第一个参数都为this的指向对象,后续参数会有差别

1. call,apply,bind——无额外参数传递

        1.1 call无额外参数传递用法

 obj.myFun.call({ name, r, q: '天音波-回音击' })

        1.2 apply无额外参数传递用法

obj.myFun.apply({ name, r, q: '天音波-回音击' })

        1.3 bind无额外参数传递用法

obj.myFun.bind({ name, r, q: '天音波-回音击' })()

        小结

无参数传递的时候,call 和 apply的写法是一致的,而bind因为返回的是一个新的函数,所以我们必须需要去调用一下,故bind(obj)()

2. call,apply,bind——额外参数传递

首先写个最基础的

        const name = '李青';
        const r = '神龙摆尾';
        const obj = {
            name: '盲僧',
            q: '天音波-回音击',
            myFun(arg1, arg2, ...args) {
                console.log(this)
                console.log('arg1===>', arg1)
                console.log('arg2===>', arg2)
                console.log('args===>', args)
                console.log('name===>', this.name)
                console.log('q===>', this.q)
                console.log('r===>', this.r)
            }
        }
        obj.myFun()

页面输出:

 没什么毛病,剩下就需要我们去更改this指向,并且向myFun中传递arg参数

       2.1 call额外参数传递用法

obj.myFun.call({ name, r, q: '天音波-回音击' }, '金钟罩/铁布衫', '天雷破/摧筋断骨', '惩戒', '闪现')

       2.2 apply额外参数传递用法

obj.myFun.apply({ name, r, q: '天音波-回音击' }, ['金钟罩/铁布衫', '天雷破/摧筋断骨', '惩戒', '闪现'])

        2.3 bind无额外参数传递用法

obj.myFun.bind({ name, r, q: '天音波-回音击' }, '金钟罩/铁布衫', '天雷破/摧筋断骨', '惩戒', '闪现')()

        小结

很微妙的差距,首先第一个参数都是this指向的对象,这个不必多说

第一个参数后续参数
callthis指向的对象第二个第三个等等后续参数统一用逗号分割
applythis指向的对象第二个参数是一个数组,需要把所有参数都放在此数组中
bindthis指向的对象第二个第三个等等后续参数统一用逗号分割,记得调用bind生成的函数就好

以上就是有关call,apply,bind的使用与对比

3. ES6箭头函数

首先看个示例

        const name = 'ming'

        function fn() {
            console.log(this)
            setTimeout(function () {
                console.log(this.name)
            }, 0)
        }

两个this都指向全局的window对象,如何才能在setTimeout中输出的this.name值为 ming

        const name = 'ming'

        function fn() {
            console.log(this)
            setTimeout(function () {
                console.log(this.name)
            }.call(this), 0)
        }

        fn.call({ name })
        fn.apply({ name })
        fn.bind({ name })()

输出:

 

 使用箭头函数时:

        function fn1() {
            setTimeout(() => {
                console.log(this.name)
            }, 0)
        }
        fn1.call({ name })
        fn1.apply({ name })
        fn1.bind({ name })()

由此可见,箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。

4. 题外话

拿我常用的uniapp举例,经常会看到有人拿着下面的代码,问问题,问,为什么我的值不改变?

<template>
	<view>{{ key }}</view>
</template>

<script>
export default {
	data() {
		return {
			key: '123'
		};
	},
	onLoad() {
		uni.showModal({
			title: '提示',
			content: '这是一个模态弹窗',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					this.key = '456';
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
};
</script>

其实一眼就看出来问题所在了,this指向不对,并没有指向当前的vue实例对象,怎么修改?

        let that = this;
		uni.showModal({
			title: '提示',
			content: '这是一个模态弹窗',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					that.key = '456';
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

很多人这么写过,在外部声明一个变量 that也好 self也好,承接当前vue实例,通过that改变vue的数据,结果当然是可行,但是不觉得 一个vue文件中,全是let that = this给人的感觉体验很差劲吗?写一个箭头函数都这么难吗?别再整这种 let that = this,代码高大上不起来!

		uni.showModal({
			title: '提示',
			content: '这是一个模态弹窗',
			success: res => {
				if (res.confirm) {
					console.log('用户点击确定');
					this.key = '456';
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

结束!