手写call,apply,bind原创
# 手写call
// 改变当前方法的this,为传入的对象,并返回调用结果
Function.prototype.myCall = function(obj,...args){
obj.fn = this;
let res = obj.fn(...args);
return res;
}
1
2
3
4
5
6
2
3
4
5
6
# 手写apply
// 改变当前方法的this,为传入的对象,并返回调用结果
Function.prototype.myApply = function(obj,arg){
obj.fn = this;
let res = obj.fn(arg);
return res;
}
1
2
3
4
5
6
2
3
4
5
6
# 手写bind
// 改变当前方法的this,为传入的对象,并返回一个函数
// 在函数内部返回调用结果
Function.prototype.myBind = function(obj,...args){
let ctx = this;
return function(...rest){
return ctx.call(obj,...rest,...args);
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8