FACTORY X CONSTRUCTOR
The biggest difference between Builders and Factorys besides the new
operator is that Factorys return an object, whereas Constructors do not. Let's take an example:
//Fábrica
function PessoaFactory(nome){
var obj = new Object();
obj.nome = nome;
return obj;
};
//Construtor
function PessoaConstructor(nome){
this.nome = nome;
};
The factory creates a new object, directs its attributes and returns it. You could use it this way:
let pessoa1 = PessoaFactory('Pedro');
console.log(pessoa.nome) //Pedro
The Builder function works in a different way:
let pessoa2 = new PessoaConstructor('Maria');
console.log(pessoa2.nome); //Maria
So far, almost the same syntax as the Factory function, but when we use the new
operator, underneath the wads, a new empty object is created and then a call is made to the call
function passing the object that ended to be created as a context:
When you use this syntax:
let pessoa2 = new PessoaConstructor('Maria');
console.log(pessoa2.nome); //Maria
Underneath the cloths this happens:
let pessoa2 = {}
PessoaConstructor.call(pessoa2, 'Maria');
console.log(pessoa2.nome); //Maria
The PessoaConstructor
function is executed in the context of the object pessoa2
, this causes the this.nome
within the constructor function to be an attribute of the object pessoa2
, which receives the parameter passed to the constructor function ;