
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
以上就是JavaScript 中链式调用是如何实现的?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号