call、apply和bind的区别
call、apply和bind的区别
-
call和apply被称为立即调用函数执行,函数调用call或apply方法后会立即执行函数。两个方法的用法相似,但不同点在于传递的参数。 -
bind方法被函数调用后不会立即执行函数。 -
这三种方法中传递的第一个参数都是修改
this指向,this指向传递的一个参数
1、call
call第一个参数传递的是修改this指向的参数,后面的参数是执行函数时传递给函数的参数,可以不传递。- 在非严格模式下,如果不传第一个参数,或者第一个参数是
null或undefined,this都指向window
let fun = function(a,b){
console.log(this,a,b);
}
let obj = {name:"obj"};
fun.call(obj,1,2); // this:obj a:1 b:2
fun.call(1,2); // this:1 a:2 b:undefined
fun.call(); // this:window a:undefined b:undefined
fun.call(null); // this=window a=undefined b=undefined
fun.call(undefined); // this=window a=undefined b=undefined
- 在严格模式下,
this指向第一个参数,包括null和undefined,如果不传第一个参数this就是undefined
"use strict"
let fun = function(a,b){
console.log(this,a,b);
}
let obj = {name:"obj"};
fun.call(obj,1,2); // this:obj a:1 b:2
fun.call(1,2); // this:1 a:2 b=undefined
fun.call(); // this:undefined a:undefined b:undefined
fun.call(null); // this:null a:undefined b:undefined
fun.call(undefined); // this:undefined a:undefined b:undefined
2、apply
apply与call的用法相似,但apply仅仅有两个参数,第一个参数依然是修改this指向,第二个参数传递的是一个数组。
let fun=function(arr){
console.log(this,arr)
}
let obj = {name:"obj"};
fun.apply(obj,[1,2,3]);// this:obj arr:[1,2,3]
- 拓展:我们可能会遇到这种情况,需要求一个数组中的最大数,通常使用的办法是将数组排序取最大的那一个,也有人可能会想到
Math函数中的max方法,但是max方法中传递的是一个个数,此时我们就可以使用apply将数组传递给Math.max()
let arr=[3,6,8,45,12,96,20,2,13]
console.log(Math.max.apply(null,arr))// 96
3、bind
bind的用法和call用法一模一样,区别在于不会立即执行函数
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX());// undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());// 42
const boundGetX1 = unboundGetX.call(module);
console.log(boundGetX1);// 42
const boundGetX2 = unboundGetX.apply(module);
console.log(boundGetX2);// 42

浙公网安备 33010602011771号