What is the difference between Constructors and Factories in JS?

0

Studying this question, I think the 2 seem ALMOST the same thing, but while the Factory returns an object when the function is executed (properties and functions do not use this , in this case closures are used) the constructor needs to be called with the keyword new (create a new object and then this for this new created object).

In addition factories can do encapsulation, returning only what we want the user to see.

Is that it? I'm wrong? Even though I think I know, I was pretty confused in that part.

    
asked by anonymous 15.06.2018 / 03:59

1 answer

2

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 ;

    
16.06.2018 / 20:50