What is the difference between Constructors and Factories in JS?

Asked

Viewed 403 times

0

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

In addition, Factories can encapsulate, returning only what we want the user to see.

Is that it? Am I mistaken? Even though I know I was very confused in this part.

1 answer

2

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.