JavaScript-bind-call-apply改变this指向

本文详细介绍了JavaScript中的this关键字,以及如何通过bind、call和apply方法改变函数内部的this指向。bind方法返回一个新的函数,允许预设this和参数;call和apply则直接调用函数,它们都能改变this,但传递参数的方式不同,call接受逗号分隔的参数,apply使用数组传递参数。
摘要由CSDN通过智能技术生成

1.this是什么?

谁调用当前函数或者方法, this就是谁

2.这三个方法的作用是什么?

这三个方法都是用于修改函数或者方法中的this

2.1.bind方法作用

修改函数或者方法中的this为指定的对象, 并且会返回一个修改之后的新函数

注意点: bind方法除了可以修改this以外, 还可以传递参数, 只不过参数必须写在this对象的后面

 		function test(a, b) {
            console.log(a, b);
            console.log(this);
        }
        test(10, 20);
        window.test();
        let fn = test.bind(obj, 10, 20);
        fn();
		function Person() {
            this.name = "lnj";
            this.say = function () {
                console.log(this);
            }
        }
        let p = new Person();
        p.say();
        // bind
        let fn = p.say.bind(obj);
        fn()

2.2.call方法作用

修改函数或者方法中的this为指定的对象, 并且会立即调用修改之后的函数

		function test(a, b) {
            console.log(a, b);
            console.log(this);
        }
        test.call(obj, 10, 20);
		function Person() {
            this.name = "lnj";
            this.say = function () {
                console.log(this);
            }
        }
        let p = new Person();
        p.say();
        // call
        p.say.call(obj);

注意点: call方法除了可以修改this以外, 还可以传递参数, 只不过参数必须写在this对象的后面

2.3.apply方法作用

修改函数或者方法中的this为指定的对象, 并且会立即调用修改之后的函数

注意点: apply方法除了可以修改this以外, 还可以传递参数, 只不过参数必须通过数组的方式传递

		function test(a, b) {
            console.log(a, b);
            console.log(this);
        }
        test.call(obj,[10, 20]);
		function Person() {
            this.name = "lnj";
            this.say = function () {
                console.log(this);
            }
        }
        let p = new Person();
        // p.say();
        // apply
        p.say.apply(obj);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值