bind,call,apply方法的实现
1.call 方法:第一个参数为 this 指向,第二个参数及以后 为传入执行函数的参数。
function myCall(context){
const arg = [...arguments].slice(1); //复制第二个以后的参数 用于传入执行函数 ,此处arguments 为类数组所以不具有数组的一些操作方法,所以需要先进行转换
const target = this; // call 方法内的 this ,此this 为调用call方法的函数
context = context ? Object(context) : window; //当传入的为 undefined/null 或者不传那么this默认指向window, 此处使用 Object 转换 是防止 传入 原始数据类型 eg: number string 等
context.fn = target;//为传入的 this 对象添加函数属性,值为调用call方法的函数,以此来确定this指向为传入的对象
const result = context.fn(...arg);
delete context.fn // 执行完成之后删除新增属性
return result; //将结果返回
}
2.apply方法: 第一个参数为 this 指向 ,第二个参数为一个数组, 只会将第二个参数传入函数,后续参数将不会传入。
function myApply(context){
const arg = arguments[1];
if(!(arg instanceof Array)){ //如果第二个参数 不为数组 那么抛出错误
throw new Error('CreateListFromArrayLike called on non-object');
}
const target = this;
context = context ? Object(context) : window; //当传入的为 undefined/null 或者不传那么this默认指向window, 此处使用 Object 转换 是防止 传入 原始数据类型 eg: number string 等
context.fn = target;
const result = context.fn(...arg);
delete context.fn;
return result
}
3.bind方法: 第一个参数 为this指向,第二个参数及以后 为传入执行函数的参数,并且执行之后会返回一个绑定this 指向的函数
function myBind(context){
const bindArg = [...arguments].slice(1);// 拷贝bind 方法 第二个以后的参数
const target = this; // 保存 调用bind方法的函数 用于后续使用
return function(){
target.myApply(context,[...arguments].concat(bindArg ));
}
}