修改this指向的时候 首先会想到使用call/apply/bind。其中call/apply在修改this的同时还会执行方法;bind则是返回一个修改了this的boundFunction,并且未执行。
- call/apply只是参数的不同
var fn = function (arg1, arg2) {
// do something
};
fn.call(this, arg1, arg2); // 参数散列
fn.apply(this, [arg1, arg2]) // 参数使用数组包裹
- 自写实现 ** call
Function.prototype.call_ = function(obj){
obj = obj ? Object(obj) : window;
obj.fn = this;
let args = [...arguments].slice(1);
let result = obj.fn(args);
delete obj.fn;
return result;
}
** apply
Function.prototype.apply_ = function(obj,arr){
obj = obj ? Object(obj) : window;
obj.fn = this;
let result;
if(!arr){
result = obj.fn();
}else{
result = obj.fn(...arr);
}
delete obj.fn;
return result;
}
** bind
Function.prototype.bind_ = function(context){
let ctx = context ? JSON.parse(JSON.stringify(content)) : window;
ctx.fn = this;
const args = Array.from(arguments).slice(1);
return function(){
const allArgs = args.concat([Array.from(arguments)]);
retutn allArgs.length > 0 ? ctx.fn(...allArgs) : ctx.fn();
}
}