bind,apply,call的区别
- 函数体中有
this
- 用来指定函数中的
this
是谁
1. apply/call
bind
/call
两者是差不多的区别在于,两者的参数不同
- 参数一:需要绑定的
this
- 其他参数:
call
直接传递参数apply
传递参数的数组
const name = 'Jack'
function fn (a,b){
console.log(name,a,b)
console.log(this.name)
this.sayName()
}
const Jim = {
name:'Jim',
sayName:function(){
console.log('sayName ' + this.name)
}
}
const Aim = {
name:'Aim',
sayName(){
console.log('sayName ' + this.name)
}
}
fn.call(Jim,2,3)
fn.apply(Aim,[2,3])
让我们看看打印结果
2. bind
bind
方法会返回一个新的函数,他的用法和call
类似。
- 参数一:需要绑定的
this
- 其他参数:直接传递参数,详情点击
在上面的例题中,我们可以直接把call
变成bind
,然后加上一个括号()
,bind
返回的是一个函数,需要调用。得到的结果是相同的。
fn.bind(Jim,2,3)()
一般的使用习惯
const fun = fn.bind(Jim)
fun(2,3)