1 call()
fun.call(thisArg, arg1, arg2, ...)
- thisArg:在 fun 函数运行时指定的 this 值
- arg1,arg2:传递的其他参数 返回值就是函数的返回值,因为它就是调用函数。因此当我们想改变 this 指向,同时想调用这个函数的时候,可以使用 call,比如构造函数的继承。举例如下:
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
function Son(uname, age) {
Father.call(this, uname, age);
}
var son = new Son('刘德华', 18);//Son继承了Father中的属性
2 apply()
fun.call(thisArg, arg1, arg2, ...)
- thisArg:在fun函数运行时指定的 this 值
- argsArray:传递的值,必须包含在数组里面 返回值就是函数的返回值,因为它就是调用函数。因此 apply主要跟数组有关系,比如使用 Math.max() 求数组的最大值。举例如下:
var arr = [3, 45, 12, 68, 36];
var arr1 = ['red', 'pink'];
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
console.log(max, min); //返回 68 3
3 bind()
fun.bind(thisArg, arg1, arg2, ...)
- thisArg:在 fun 函数运行时指定的 this 值
- arg1,arg2:传递的其他参数 返回由指定的 this 值和初始化参数改造的原函数拷贝。因此当我们只是想改变 this 指向,并且不想调用这个函数的时候,可以使用 bind。如计时器函数,举例如下:
var btns = document.querySelectorAll('button');//获取按钮
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
this.disabled = true;
setTimeout(
function () {
this.disabled = false;
}.bind(this),//通过bind将setTimeout中this的指向由原来的window改成btn按钮。
2000
);
};
}
4 三者的区别
相同点:
都可以改变函数内部的this指向
不同点:
- call 和 apply 会调用函数, 并且改变函数内部this指向.
- call 和 apply 传递的参数不一样, call 传递参数 aru1, aru2..形式 apply 必须数组形式[arg]
- bind 不会调用函数, 可以改变函数内部this指向.
应用
- call 经常做继承.
- apply 经常跟数组有关系. 比如借助于数学对象实现数组最大值最小值
- bind 不调用函数,但是还想改变this指向. 比如改变定时器内部的this指向.