patkua@work

A builder pattern implementation in Javascript

We’re using the builder pattern on our javascript project, as it useful for starting off with a set of defaults, but is clear when we want to override particular values. Although there are a few places on the net that describe who uses the builder pattern in javascript, they don’t really provide an implementation.

Here’s one that works for us:

var Builder = function() {
  var a = "defaultA";
  var b = "defaultB";
  
  return {
      withA : function(anotherA) {
        a = anotherA;
        return this;
      },
      withB : function(anotherB) {
        b = anotherB; 
        return this;
      },
      build : function() {
        return "A is: " + a +", B is: " + b;
      }
  };
};

var builder = new Builder();

console.log(builder.build());

var first = builder.withA("a different value for A").withB("a different value for B").build();

var second = builder.withB("second different value for B").build();

var third = builder.withA("now A is different again").build();

console.log(first);
console.log(second);
console.log(third);
Exit mobile version