封装函数 f,使 f 的 this 指向指定的对象
- call()、bind()、apply()的用法,改变this的指向,区别在于
f.call(obj, arg1, arg2…),
f.bind(obj, arg1, arg2,…)(),
f.apply(obj, [arg1, arg2, .])
function bindThis(f, oTarget) {
return function() {
return f.apply(oTarget, arguments)
}
}
function bindThis(f, oTarget) {
return f.bind(oTarget)
}
function bindThis(f, oTarget) {
return function() {
return f.call(oTarget, ...arguments)
}
}
例:
function fn(x, y) {
console.log(this)
console.log(x + '-' + y)
console.log(this.name + '-' + this.age)
}
var persoon = {
name: 'chen',
age: 18
}
fn.call(persoon, 'hh', 20)
function bindThis(f, oTarget) {
return function(...args){
oTarget.f=f;
return oTarget.f(...args);
}
}
- 利用循环的方法,使得返回值的变化
function bindThis(f, oTarget) {
if(f.bind){
return f.bind(oTarget);
}else {
return function(){
return f.apply(oTarget,arguments);
};
}
}