
js 链式调用背后的秘密
在 javascript 中,可以使用链式调用来简洁地执行一系列操作。例如,以下代码演示了链式调用:
sint(1,2).j(10) // 13
但是,这种实现方式需要使用 new 关键字来实例化一个对象,才能访问 j 方法。是否有办法直接使用 sint(1,2).j(10) 来获得结果呢?
答案是肯定的。我们可以利用 javascript 中的代理对象来实现这种功能。
立即学习“Java免费学习笔记(深入)”;
function sint(a, b) {
this.val = a + b;
}
sint.prototype.j = function (e) {
return this.val + e;
};
const proxysint = new proxy(sint, {
construct: function (target, args) {
const instance = new target(...args);
return instance.j(...args);
}
});
console.log(proxysint(1, 2)); // 13在这个实现中,我们创建了一个代理对象 proxysint 来拦截 sint 函数的构造函数。当这个代理对象被调用时,它会创建一个普通的 sint 对象,然后立即调用 j 方法,将构造函数参数作为参数传递给它。
因此,我们可以直接使用 proxysint(1,2) 来得到结果,而不需要使用 new 关键字或手动调用 j 方法。
为了更彻底地重写示例函数,我们可以结合以下想法,直接打印不用经过参与计算:
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;
};
console.log(new Sum(1, 2, 3).add(4).add(5).value); // 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号