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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律