改变this指向
题目:封装函数 f,使 f 的 this 指向指定的对象
⚠️改变this指向有三种方式 call、bind、apply
call、apply-----只有一个区别,就是 call() 方法接受的是若干个参数的列表,而 apply() 方法接受的是一个包含多个参数的数组。
三个第一个参数都是想要改变的this的指向
call apply bind 总结:
相同点: 都可以改变函数内部的this指向.
区别点:call 和 apply 会调用函数, 并且改变函数内部this指向. call 和 apply 传递的参数不一样, call 传递参数 aru1, aru2…形式 apply 必须数组形式[arg] ;bind 不会调用函数, 可以改变函数内部this指向.
方法1:
function bindThis(f, oTarget) {
return f.bind(oTarget);
}
方法2:
function bindThis(f, oTarget) {
return function(){
return f.apply(oTarget,arguments)
}
}
方法3
function bindThis(f, oTarget) {
return function(x,y){
return f.call(oTarget,x,y)
}
}
参考博文
添加链接描述