相同点: 都可以改变函数内部的this指向.
区别点:
- call 和apply会调用函数并組改变函数内部this指向.
- call 和apply传递的参数不一样, call传递参数aru1, aru2…形式apply 必须数组形式[arg]
- bind 不会调用函数,可以改变函数内部this指向.
- 主要应用场景:
- call经常做继承.
- apply 经常跟数组有关系.比如借助于数学对象实现数组最大值最小值
- bind 不调用函数,但是还想改变this指向.比如改变定时器内部的this指向.
// call
function Father(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
console.log(this.name, this.age, this.sex);
}
function Son(name, age, sex) {
Father.call(this, name, age, sex);
}
new Son('刘德华', 54, '男');
//apply的主要应用,可以利用apply借助数学内置对象求最大值
var arr = [13, 35, 47, 9, 5, 99, 66];
// var Max = Math.max.apply(null, arr);
var Max = Math.max.apply(Math, arr);
var Min = Math.min.apply(Math, arr);
console.log(Max, Min);
//1、 bind 不会调用函数,只会改变this指向
//2、返回的是改变this函数后,产生的新函数
// 3、如果有的函数我们不需要立即调用,但是又想改变这个函数内部的this指向此时用bind
f();
var oBtn = document.querySelectorAll('button');
for (var i = 0; i < oBtn.length; i++) {
oBtn[i].onclick = function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false; // 定时器函数里面的this指向的是window
}.bind(this), 2000) // 定时器函数外面的this指向的是btn
}
}