彻底掌握call,apply,bind用法,相同点与不同点,应用场景

231 阅读2分钟

call()语法: 函数名.call(修改this的指向, arg1, arg2...)

apply()语法: 函数名.apply(修改this的指向, [arg1, arg2...])  

bind()不会调用函数,和call的传参方式一样,但是得命名一个 返回值在返回这个函数

1.call可以调用函数,call可以改变this指向, call可以实现继承,继承构造函数中的属性

    var o = {
        name: 'andy'
    }

    function fn(a, b) {
        console.log(a + b); //3
        console.log(this); //Object-->o{name:'andy'}
    }
    fn.call(o, 1, 2);
    

构造函数实现继承

    function Baba(uname, upassword) {
        this.uname = uname;
        this.upassword = upassword;
    }

    function Erzi(uname, upassword) {
        Baba.call(this, uname, upassword)
    }
    var yonghu = new Erzi('张三', '259011');
    console.log(yonghu);

2.apply

    var b = {
        name: 'andy'
    }

    function Fn2(a, b) {
        console.log(a + b); //3
        console.log(this); //Object-->b{name:'andy'}
    }
    Fn2.apply(b, [1, 2]);
    

apply的主要应用:math求最大值

    var arr8 = [1, 4, 2, 3, 3333, 999, 302, 380, 338, 33]
    var max = Math.max.apply(null, arr8);
    var min = Math.min.apply(null, arr8);
    console.log(max, min);
    

3.bind()方法,不会调用函数,但能改变函数内部的this指向

    var j = {
        name: 'andy'
    }

    function Fn3(a, b) {
        console.log(this); //Object-->j{name:'andy'}
        console.log(a + b);
    }
    var fn3 = Fn3.bind(j, 1, 3);
    fn3();
    

bind的应用场景:如果有的函数我们不需要立即调用,但是又想改变这个函数的this指向时。

    //例:我们有一个按钮,当我们点击了之后,就禁用这个按钮, 3秒之后再开启这个按钮
    var btn = document.querySelector('button');
    //方案一:备份上下文
    // btn.onclick = function() {
    //     this.disabled = true; //btn
    //     var _this = this; //备份btn的上下文,供下文使用
    //     setTimeout(function() {
    //         _this.disabled = false; //定时器的this指向window
    //     }, 3000)
    // };
    //方案二:bind改变
    btn.onclick = function() {
        this.disabled = true; //btn
        setTimeout(function() {
            this.disabled = false; //定时器的this指向window
        }.bind(this), 3000)
    }
    

区别:call,apply,bind总结

相同点:都可以改变函数的this指向

不同点:

1.call和apply会调用函数,并且改变函数内部的this指向

2.call和apply传递的参数不一样,call传递参数aru1,aru2,...形式,apply传递[arg]形式

3.bind不会直接调用函数,需要再定义再调用

主要应用场景

1.call经常作继承

2.apply跟数组有关

3.bind不用立即调用函数但又需要改变this指向