生成器模式不向对象添加值

时间:2017-09-26 11:12:35

标签: javascript ecmascript-6 builder-pattern

我正在尝试关注ES6 Builder pattern,因为我现在开始构建一个更复杂的对象。

到目前为止,我有:

class Opinion {
  constructor () {
    this.nuts = '';
  }
}

class Builder {
  constructor () {
    this.opinion = new Opinion();
  }

  withNuts (nuts) {
    this.nuts = nuts;
    return this;
  }

  build () {
    return this.opinion;
  }
}

export default Builder;

使用的是:

import Builder from '../helpers/builder/opinion';
const defaultOpinion = new Builder()
    .withNuts(2.9)
    .build();

输出:

opinion: {"nuts":""}

为什么它没有被构建到对象中?

另外,当我想将一个对象传递回Builder中进行编辑时,它也会返回空白(这是有意义的),但是我当前的Builder设置是否允许这样做?例如:

 const opinionChange = new Builder(defaultOpinion)
    .withNuts(0.8)
    .build();

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

您错过了分配给this.opinion.nuts,而是在对象上创建了自己的属性nuts。替换为

withNuts (nuts) {
    this.opinion.nuts = nuts;
    return this;
}

工作代码



class Opinion {
  constructor () {
    this.nuts = '';
  }
}

class Builder {
  constructor () {
    this.opinion = new Opinion();
  }

  withNuts (nuts) {
    this.opinion.nuts = nuts; // this.opinion.nuts
    return this;
  }

  build () {
    return this.opinion;
  }
}


const defaultOpinion = new Builder()
    .withNuts(2.9)
    .build();
    
console.log(defaultOpinion);




答案 1 :(得分:1)

withNuts方法应更新this.opinion.nuts而不是this.nuts

withNuts (nuts) {
    this.opinion.nuts = nuts;
    return this;
}