
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)); // 15console.log(new Sum(1, 2, 3).add(4).add(5) + 20); // 35
以上就是JavaScript 中链式调用是如何实现的?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1497479.html
微信扫一扫
支付宝扫一扫