废话不多说,直接上代码
MyCall
Function.prototype.myCall = function(context, ...args){
context = context || window;
//改变this的指向
context.fn = this;
const result = context.fn(...args);
//记得将其删除
delete context.fn
return result
}
MyApply
和myCall基本一样,主要是传入的为数组,需要注意
Function.prototype.myApply = function(context, argsArray){
context = context || window;
context.fn = this;
const result = context.fn(...argsArray);
delete context.fn
return result
}
MyBind
myBind核心在于根据传入参数,返回的是一个函数
Function.prototype.myBind = function(context, ...args){
let fn = this; //保存这里的this指向,以便闭包可以访问到context;
return functon (...innerArgs){
//这里的innerArgs为之后传入的参数
return fn.apply(context, args.concat(innerArgs))
}
}