call、apply、bind区别

369 阅读2分钟

(一)call()方法

call() 方法是使用一个指定的this值和单独给出的一个或多个参数来调用一个函数。

        var sum = {
            add: function () {
                return this.a + '---' + this.b
            }
        }
        var sum1 = {
            a: 12,
            b: 34
        }
        var sum2 = {
            a: 56,
            b: 78
        }
        sum.add.call(sum1);
        console.log(sum.add.call(sum1));//12---34
        console.log(sum.add.call(sum2));//56---78

带参数的call()方法

call() 方法可接受参数:
实例

        var sum = {
            add: function (c, d) {
                return this.a + '---' + this.b + '---' + c + '---' + d
            }
        }
        var sum1 = {
            a: 12,
            b: 34
        }
        sum.add.call(sum1, 123, 456);
        console.log(sum.add.call(sum1, 123, 456));//12---34---123---456

(二)apply()方法

apply( ) 方法调用一个具有给定this值的函数,以及作为一个数组(或类似数组对象)提供的参数。
第一个参数: this 指向
第二个参数: 一个数据或者类数组对象
如果没有传递参数:则为全局变量

        var x=0;
        function test(){
            alert(this.x);
        }
        var o={};
        o.x=1;
        o.m=test;
        o.m.apply();//0
        o.m.apply(o);//1

(三) bind

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

        const sum = {
            x: 18,
            add: function () {
                return this.x;
            }
        };
        const sum1 = sum.add;
        console.log(sum1());// expected output: undefined
        const sum2 = sum1.bind(sum);
        console.log(sum2());// expected output: 18

apply()和call()的区别

call方法的作用和apply()方法类似,区别就是call()方法是使用参数列表,而apply()方法接受的是一个参数数组

apply、call和bind之间微妙的差距

call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象,第二个参数差别就来了:
call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,直接放到后面。
apply 的所有参数都必须放在一个数组里面传进去。
bind 除了返回是函数以外,它 的参数和 call 一样。
当然,三者的参数不限定是 string 类型,允许是各种类型,包括函数 、 object 等等!