0

I am attempting to follow the ES6 Builder pattern, as I am now starting to construct a more complex object.

So far I have:

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;

Which is used:

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

That outputs:

opinion: {"nuts":""}

Why is it not being built into the object?

Also, when I want to pass an object back into the Builder, to be edited, it also returns blank (which makes sense), but would my current Builder set up allow this? For example:

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

Many thanks for your help.

  • You never use the `.nuts` of the builder anywhere? Where did you expect them to end up? – Bergi Sep 26 '17 at 11:14

2 Answers2

1

You missed to assign to the this.opinion.nuts, instead you create an own property nuts on the object. Replace with this

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

Working Code

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);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Thank you, all values are returned! Would it be easy enough to change the builder to allow an object to be passed in and changed? Like this for example: ```const opinionChange = new Builder(defaultOpinion) .withNuts(0.8) .build();``` –  Sep 26 '17 at 11:36
  • It also an approach, you need to change 2 constructors – Suren Srapyan Sep 26 '17 at 11:41
  • Could you point me in the right direction please? How could I achieve this? Thank you! –  Sep 26 '17 at 12:18
  • 1
    Make the `constructor ()` to take an parameter, same for the `Opinion` and when you call `new Opinion()`, pass the parameter – Suren Srapyan Sep 26 '17 at 12:26
  • Thank you for your reply! Like this: ```class Builder { constructor (build) { this.opinion = new Opinion(build); }``` and ```class Opinion { constructor (build) { this.nuts = build.nuts; } }``` ? –  Sep 26 '17 at 12:28
1

The withNuts method should update this.opinion.nuts instead of this.nuts:

withNuts (nuts) {
    this.opinion.nuts = nuts;
    return this;
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209