在javascript中阅读管道方案时,我发现了以下片段:
value.one().two().three()
我想知道是否有办法实现这样的东西。
假设它应该是这样工作的:
one().two().three() // "1-2-3"
two().one().three() // "2-1-3"
two().two().two().one() // "2-2-2-1"我唯一能做到的就是:
const one = () => ({ two: () => ({ three: () => "1-2-3" }) });
one().two().three() // 1-2-3但这显然不是解决问题的灵活办法。
发布于 2022-09-25 08:29:01
很明显,这被称为"Fluent接口“,它可以这样实现
function Num() {
this.string = ''
this.one = () => {
this.string += '-1';
return this;
}
this.two = () => {
this.string += '-2';
return this;
}
this.three = () => {
this.string += '-3';
return this;
}
this.value = () => {
return this.string.substring(1);
}
}
const num = new Num()
console.log(num.one().two().two().two().three().value())https://stackoverflow.com/questions/73842993
复制相似问题