javascript - Chain functions in JavaScript
问题描述
Is there a way to chain functions in JavaScript so when last function in chain is called we take into consideration all function in chain that was specified. Basically what I am trying to do is the same thing express-validator does: Something like this:
check('password').passwordValidator().optional();
I want to be able to call
check('password').passwordValidator();
and
check('password').passwordValidator().optional();
解决方案
所以你正在寻找一种建造者模式?你可以这样做:
class Foo {
_passwordValidator = false;
_optional = false;
passwordValidator() {
this._passwordValidator = true;
return this;
}
optional() {
this._optional = true;
return this;
}
doThing() {
if (this._optional) { /* ... */ }
if (this._passwordValidator) { /* ... */ }
}
}
const foo = new Foo().passwordValidator().optional();
foo.doThing();
编辑:为了更直接地回答你的问题,没有办法等到当前的方法调用链完成后再做某事;您必须调用doThing()
示例中的方法来表示您现在确实想要执行此操作。
推荐阅读
- angular - Angular an obj is lost upon page reload
- python - 如何删除文件的特定部分
- c++ - Qt3d。在三角形上绘制透明 QSphereMesh
- python - Python:Pandas 在 Pandas (Dataframe) 中查找文本的可用性
- python - 如何使用python从ffmpeg管道输出?
- javascript - 如何返回地图
- docker - 我想在本地服务器上的 IIS 上运行一个 docker 配置的项目
- mysql - 如何在同一个表中使用 SQL 连接中的值总和
- java - 将域对象与业务逻辑耦合
- python - python中不同模块的多个日志文件