首页 > 解决方案 > 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();

标签: javascriptnode.jsexpress-validator

解决方案


所以你正在寻找一种建造者模式?你可以这样做:

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()示例中的方法来表示您现在确实想要执行此操作。


推荐阅读