JavaScript中的链函数 [英] Chain functions in JavaScript
问题描述
有没有一种方法可以链接JavaScript中的函数,因此当调用链中的最后一个函数时,我们会考虑指定的链中的所有函数. 基本上我想做的是同一件事 express-validator 做: 像这样:
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();
我希望能够打电话
check('password').passwordValidator();
和
check('password').passwordValidator().optional();
推荐答案
So you're looking for a sort of builder pattern? You can do that like this:
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()
的方法,以表明您实际上现在想做这件事.
to more directly answer your question, there is no way to wait to do something until the current chain of method calls is done; you have to call a method like doThing()
in the example to signal that you actually want to do the thing now.
这篇关于JavaScript中的链函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!