手写bind,call,apply,柯里化
bind
Function.prototype.myBind = function(context = window) {
let obj = { ...context };
obj.fn = this;
return obj.fn;
};
call
Function.prototype.myCall = function(context = window, ...arr) {
context.fn = this;
let result = context.fn(...arr);
delete context.fn;
return result;
};
apply
Function.prototype.myApply = function(context = window, arr) {
context.fn = this;
let result = context.fn(...arr);
delete context.fn;
return result;
};
柯里化实现a(1,2,3)或a(1)(2)(3)
function currying(fn, ...arr1) {
return function(...arr2) {
let arr = [...arr1, ...arr2];
if (arr.length < fn.length) {
return currying(fn, ...arr);
} else {
return fn.apply(this, arr);
}
};
}
function add(x, y, z) {
console.log(x + y + z);
return x + y + z;
}
let a = currying(add);

浙公网安备 33010602011771号