手写call
Function.prototype.newcall = function(par){
//有参用参,无参指向window
par = par || window;
//添加一个属性 赋值给this
par.fn = this;
//arguments [function,参数] 截取参数 为从funciton后的形成新的数组[par];
var arg = [...arguments].slice(1);
//将数组作为入参给定义的 调用方法 ...arg将arg转为用逗号分隔的参数序列
var result = par.fn(...arg);
//原来par是没有fn的,删除掉,不影响继承结构
delete par.fn;
return result;
};
手写apply
// 思路:将要改变this指向的方法挂到目标this上执行并返回
Function.prototype.myapply = function (ctx) {
ctx = ctx||window;
ctx.fn = this;
var result;
//arguments 此时为 [fn ctx(),[参数];
if(arguments[1]){
//[参数]对应apply传的数组
result =ctx.fn(...arguments[1]);
}else{
result =ctx.fn();
}
delete ctx.fn;
return result;
}
验证方法是否生效
function add(a,b){
return a+b;
}
function sub(a,b){
return a - b;
}
console.log(add.newcall(sub,10,15));
console.log(add.myapply(sub,[10,20]));