call apply bind

111 阅读1分钟

call apply bind的相同点和不同点

call(this,形参1,形参2,...) apply(this,[形参1,形参2,...]) bind(this,形参1,形参2,...)

相同点: 改变函数内部this的指向
不同点:
    1. call 和 apply会调用函数
    2. call和apply传递参数不一样, call是aru1, aru2形式传递, apply数组形式传递
    3. bind不会调用函数, 返回的是原函数改变this产生的新函数
应用场景
    1. call经常做继承 ,继承父类构造函数里的属性
    2. apply经常跟数组有关系, 比如借助数学对象实现数组最大最小值
    3. bind不调用函数, 但想改变this指向, 比如定时器内部this指向
代码示例

 function Father(name) {
        this.name = name
    }
    function Son(name) {
        Father.call(this, name);
    }
    var s = new Son('xiao');
-------------------------------------------------------------------
 var btn = document.getElementsByTagName('button')[0];
    btn.onclick = function() {
        // var that = this
        this.disabled = true
        setTimeout(function() {
            this.disabled = false;
        }.bind(this), 2000)
    }