# 实现链式调用
# 昨日回顾
柯里化
function add(...args) {
return args.reduce((a, b) => a + b, 0);
}
function curry(fn) {
let args = [];
return function temp(...newArgs) {
if (newArgs && newArgs.length) {
args = [...args, ...newArgs];
return temp;
} else {
const result = fn.apply(this, args);
args = [];
return result;
}
};
}
const addCurry = curry(add);
console.log(addCurry(1)(2)(3)(4, 5)()); //15
console.log(addCurry(1)(2)(3, 4, 5)()); //15
console.log(addCurry(1)(2, 3, 4, 5)()); //15
# 今日解题
链式调用 -> 调用完方法将自身实例返回
/// 01
function Class1() {
console.log("初始化");
}
Class1.prototype.method = function (param) {
console.log(param);
return this;
};
const c1 = new Class1();
// 由于new在实例化的时候this会指向创建的对象,所以this.method这个方法会在原型链中找到
c1.method("第一次调用")
.method("第二次调用")
.method("第三次调用")
.method("第四次调用");
// 02
const obj = {
a: function () {
console.log("a");
return this;
},
b: function () {
console.log("b");
},
};
obj.a().b();
// 03 类
class Math {
constructor(value) {
this.hasInit = true;
this.value = value;
if (!value) {
this.hasInit = false;
this.value = 0;
}
}
add() {
let args = [...arguments];
let initValue = this.hasInit ? this.value : args.shift();
const value = args.reduce((prev, curv) => prev + curv, initValue);
return new Math(value);
}
minus() {
let args = [...arguments];
let initValue = this.hasInit ? this.value : args.shift();
const value = args.reduce((prev, curv) => prev - curv, initValue);
return new Math(value);
}
}
let test = new Math();
test.add(222, 333, 444).minus(333, 222);
// 04 原型链
Number.prototype.add = function () {
let _that = this;
_that = [...arguments].reduce((prev, curv) => prev + curv, _that);
return _that;
};
Number.prototype.add = function () {
let _that = this;
_that = [...arguments].reduce((prev, curv) => prev - curv, _that);
return _that;
};
let num = 0;
let newNum = num.add(222, 333, 444).minus(333, 222);