JavaScript 中的链式函数

Blz*_*Blz 4 javascript node.js express-validator

有没有办法在 JavaScript 中链接函数,所以当调用链中的最后一个函数时,我们会考虑链中指定的所有函数。基本上我想做的事情与express-validator 做的事情是一样的:像这样:

check('password').passwordValidator().optional();
Run Code Online (Sandbox Code Playgroud)

我希望能够打电话

check('password').passwordValidator();
Run Code Online (Sandbox Code Playgroud)

check('password').passwordValidator().optional();
Run Code Online (Sandbox Code Playgroud)

Blz*_*Blz 9

我最终使用了@coolreader18 的建议。这正是我所寻找的。

function func(val) {
    this._optional = false;
    this._check = false;
    
    const doStaff = (message = 'Doing staff') => {
        console.log(message);
        return;
    };


    return {
        check: function(n) {
            this._check = true;
            return this;
        },
        optional: function(n) {
            this._check = false;
            this._optional = true;
            return this;
        },
        exec: function() {
            if (this._check) doStaff();
            if (this._optional) doStaff('Maybe not');
        }
    }
}

func().check().optional().exec();
Run Code Online (Sandbox Code Playgroud)


coo*_*r18 7

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

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();
Run Code Online (Sandbox Code Playgroud)

编辑:为了更直接地回答您的问题,无法等到当前的方法调用链完成后再做某事;您必须调用doThing()示例中的方法来表示您现在确实想要做这件事。

  • 我相信`passwordValidator`和`optional`都需要返回`this`才能链接,对吗? (3认同)

has*_*emi 5

var Obj = {
  result: 0,
  addNumber: function(a, b) {
    this.result = a + b;
    return this;
  },

  multiplyNumber: function(a) {
    this.result = this.result * a;
    return this;
  },
 
  divideNumber: function(a) {
    this.result = this.result / a;
    return this;
  }
}

Obj.addNumber(10, 20).multiplyNumber(10).divideNumber(10);
Run Code Online (Sandbox Code Playgroud)

链接=> https://medium.com/technofunnel/javascript-function-chaining-8b2fbef76f7f