function Person(name, age, weight, address) {
this.name = name;
this.age = age;
this.weight = weight;
this.address = address;
}
function CreatePerson(name, age) {
this.name = name;
this.age = age;
this.setWeight = function (weight) {
this.weight = weight;
return this;
};
this.setAddress = function (address) {
this.address = address;
return this;
};
this.build = function () {
return new Person(this.name, this.age, this.weight, this.address);
};
}
const student = new CreatePerson("Messi", "32")
.setWeight("80")
.setAddress("address")
.build();
console.log(student);
// Person { name: 'Messi', age: '32', weight: '80', address: 'address' }
Builder Pattern
using new ES5 Syntax
class Person {
constructor(name, age, weight, address) {
this.name = name;
this.age = age;
this.weight = weight;
this.address = address;
}
}
class CreatePerson {
constructor(name, age) {
this.name = name;
this.age = age;
}
setWeight(weight) {
this.weight = weight;
return this;
}
setAddress(address) {
this.address = address;
return this;
}
build() {
return new Person(this.name, this.age, this.weight, this.address);
}
}
const student = new CreatePerson("Messi", "32")
.setWeight("80")
.setAddress("address")
.build();
console.log(student);
// Person { name: 'Messi', age: '32', weight: '80', address: 'address' }