
javascript 中链式调用的实现
在 javascript 中,链式调用是指函数可以连续地在一个表达式中调用,而无需使用临时变量的方法。
要实现链式调用,可以采用以下方法:
使用链式调用接受“this”对象
立即学习“Java免费学习笔记(深入)”;
通过使用 this 关键字,可以将对象本身作为函数的参数。
function sint(a, b) {
this.val = a + b;
}
sint.prototype.j = function(e) {
return this.val + e;
}在函数内部定义链式调用
通过在函数内部定义另一个函数,可以实现链式调用。
function sint(a, b) {
this.val = a + b;
this.j = function(e) {
return this.val + e;
}
}使用 es6 proxy 绑定 symbol.toprimitive
通过使用 es6 proxy,可以绑定 symbol.toprimitive 方法,使其在参与计算时返回所需的值。
function sum(...args) {
this.value = args.reduce((a, b) => a + b, 0);
return new proxy(this, {
get: function (target, prop) {
if (prop === symbol.toprimitive) {
return () => target.value;
}
return target[prop];
}
});
}
sum.prototype.add = function (value) {
this.value += value;
return this;
}使用示例
// Sint 方法 console.log(Sint(1, 2).j(10)); // 13 // ES6 Proxy 方法 console.log(new Sum(1, 2, 3).add(4).add(5)); // 15 console.log(new Sum(1, 2, 3).add(4).add(5) + 20); // 35










