// bind 方法原理模拟
// bind 方法的模拟
Function.prototype.bind = function (context) {
var self = this;
var args = [].slice.call(arguments, 1);
return function () {
return self.apply(context, args);
}
}
Function.prototype.bind = function(context, ...args){
return () => {
return this.apply(context, args);
}
}
function add (a, b) {
return a + b;
}
console.log(add.bind(null, 2, 3)())
const curry = (fn, ...arg) => {
let all = arg || [],
length = fn.length;
return (...rest) => {
let _args = all.slice(0);
_args.push(...rest);
if (_args.length < length) {
return curry.call(this, fn, ..._args);
} else {
return fn.apply(this, _args);
}
}
}
const add = curry((a, b) => a + b);
const add6 = add(6);
console.log(add6(1)); //7
console.log(add6(2)); //8
var curry = function(func,args){
var length = func.length;
args = args||[];
return function(){
newArgs = args.concat([].slice.call(arguments));
if(newArgs.length < length){
return curry.call(this,func,newArgs);
}else{
return func.apply(this,newArgs);
}
}
}
function sum (a, b, c){
return a + b + c;
}
var addCurry = curry(sum);
addCurry(1,2) //3
addCurry(1)(2) //3
function add (x) {
let sum = x;
const temp = function (y) {
sum += y;
return temp;
}
temp.toString = function () {
return sum;
}
return temp;
}
console.log(add(1)(2)(3).toString())
来源:https://www.cnblogs.com/shangyueyue/p/10609943.html