[前端知识点]修改this指向
前言
js修改this指向通常有三种方法:call()、apply()、bind()一、bind()
1.直接bind()
function bindThis(f, oTarget) {
return f.bind(oTarget);
}
2.手写bind()
利用了call()和apply()
function bindThis(f, oTarget) {
let args = Array.prototype.slice.call(arguments, 2);
return function(){
return f.apply(oTarget, Array.prototype.slice.call(arguments).concat(args));
}
}
二、apply()
function bindThis(f, oTarget) {
return function(){
return f.apply(oTarget,arguments);
}
}
三、call()
function bindThis(f, oTarget) {
return function(x,y){
return f.call(oTarget,x,y);
};
}
总结
三种方法区别可参考:JavaScript 中 call()、apply()、bind() 的用法