关于bind、call、apply之间的区别
我们知道bind、call、apply是ES5中改变this指向的,改变this执行这也是他们的共同点;以下面代码为实例来解释:
function test(){
console.log("在测试")
}
function exam(){
// 通过call改变this指向
test.call(this)
}
exam() //"在测试"
function test(){
console.log("在测试")
}
function exam(){
// 通过apply改变this指向
test.apply(this)
}
exam() //"在测试"
function test(){
console.log("在测试")
}
function exam(){
// 通过bind改变this指向
let a = test.bind(this)
a()
}
exam() //"在测试"
那么他们之前也存在着不同之处,同样,我们通过代码来进行解释说明:
function a(male,str){
console.log(male+"在测试"+str)
}
function b(male,str){
// 通过call改变this指向,并传递参数
// 这里的参数写在要指定的this对象后面,参数与参数之间,参数与改变的this对象之间使用逗号隔开
//call是临时改变的,直接就是在调用函数本身
a.call(this,male,str)
}
b("male",",非常认真") //male在测试,非常认真
function a(male,str){
console.log(male+"在测试"+str)
}
function b(male,str){
// 通过apply改变this指向,并传递参数
// 这里的参数写在要指定的this对象后面,参数与参数之间使用逗号隔开,参数要写在一个数组括号里面
//apply是临时改变的,直接就是在调用函数本身
a.apply(this,[male,str])
}
b("male",",非常认真") //male在测试,非常认真
function a(male,str){
console.log(male+"在测试"+str)
}
function b(male,str){
// 通过bind改变this指向,并传递参数
//bind是永久绑定的,如果下面的代码仍然需要用到这个地方的,可以找直接写q(male,str)
//这里只是将对象与函数进行了一个绑定,返回了一个新的函数q
let q = a.bind(this)
//q执行
q(male,str)
}
b("male",",非常认真") //male在测试,非常认真