
javascript 链式函数调用的实现
在 javascript 中,链式函数调用允许我们连续调用一系列函数,而无需每次都使用新变量存储中间结果。这是通过利用函数的原型链来实现的。
实现方法:
function sint(a, b) { this.val = a + b;}sint.prototype.j = function (e) { return this.val + e;};
但是,要直接调用 sint(1,2).j(10),我们需要使用一个代理对象:
立即学习“Java免费学习笔记(深入)”;
const sum = new proxy(new sint(1, 2), { get: function (target, prop) { if (prop === 'j') { return (...args) => target.j(...args); } return target[prop]; }})
现在,我们可以直接调用 sum.j(10),它将返回 13。
扩展方法:
另一种实现方法是利用 symbol.toprimitive 符号。函数可以绑定一个 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;}
使用示例:
const sum = new Sum(1, 2, 3);sum.add(4).add(5); // 返回代理对象console.log(sum.value); // 15console.log(sum + 20); // 35
以上就是JavaScript 中如何实现链式函数调用?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1497406.html
微信扫一扫
支付宝扫一扫