首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中使用对象属性实现“管道”

在javascript中使用对象属性实现“管道”
EN

Stack Overflow用户
提问于 2022-09-25 08:19:28
回答 1查看 23关注 0票数 -1

在javascript中阅读管道方案时,我发现了以下片段:

value.one().two().three()

我想知道是否有办法实现这样的东西。

假设它应该是这样工作的:

代码语言:javascript
复制
one().two().three() // "1-2-3"

two().one().three() // "2-1-3"

two().two().two().one() // "2-2-2-1"

我唯一能做到的就是:

代码语言:javascript
复制
const one = () => ({ two: () => ({ three: () => "1-2-3" }) });

one().two().three() // 1-2-3

但这显然不是解决问题的灵活办法。

EN

回答 1

Stack Overflow用户

发布于 2022-09-25 08:29:01

很明显,这被称为"Fluent接口“,它可以这样实现

代码语言:javascript
复制
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())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73842993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档