FACTORY X CONSTRUCTOR
The biggest difference between Builders and Factorys beyond the operator new
, is that the Factorys return an object, while the Constructors do not. Let’s look at 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, arrow its attributes and returns it. You could use it this way:
let pessoa1 = PessoaFactory('Pedro');
console.log(pessoa.nome) //Pedro
The Constructor function works in a different way:
let pessoa2 = new PessoaConstructor('Maria');
console.log(pessoa2.nome); //Maria
Until then, almost the same syntax as the Factory function, but when we use the operator new
, under the cloths, a new empty object is created and a call is made to the function call
passing the object that has just been created as context:
When you use this syntax:
let pessoa2 = new PessoaConstructor('Maria');
console.log(pessoa2.nome); //Maria
Under the covers that happens:
let pessoa2 = {}
PessoaConstructor.call(pessoa2, 'Maria');
console.log(pessoa2.nome); //Maria
The function PessoaConstructor
is executed in the context of the object pessoa2
, this makes the this.nome
inside the constructor function becomes an object attribute pessoa2
, which receives the parameter passed to the constructor function;