Return all the parameters of the constructor of a function in Javascript

0

Imagine the following situation:

I have several "classes" built from javascript functions where their properties are defined inside the constructor. So:

var Pessoa = function(data) {
    this.nome     = arguments[0].nome     || '';
    this.telefone = arguments[0].telefone || '';
    ... // n parâmetros ...
    this.email    = arguments[0].email    || '';
};

The use of the arguments[0] property is used to send an object with all the properties that will be set for this Person class. Is there any way I can return all the properties I have inside the constructor of this classe ?

As far as I understand of Javascript, I probably could not do this natively. So, using a prototyped function, how can I return all the parameters defined within my constructor?

    
asked by anonymous 27.01.2017 / 14:22

2 answers

0

Well from what I realized you want to return all the parameters defined in the constructor, I just did not understand where the arguments object comes from.

We can return the parameters defined in the '%' class as follows:

Let's say the class is already declared.

var pessoa = new Pessoa(data); // instanciamos a classe

for(param in pessoa){ // aplicamos um loop
    console.log(param) // aqui serao retornados todos os parametros defenidos de Pessoa
    console.log(pessoa[param]) // aqui serao retornados os valores
}
    
27.01.2017 / 15:44
0

To know what properties an instance has you can do this:

var Pessoa = function(data) {
    this.nome     = arguments[0].nome     || '';
    this.telefone = arguments[0].telefone || '';
    // ... n parâmetros ...
    this.email    = arguments[0].email    || '';
};

var sergio = new Pessoa({nome: 'sergio', telefone: '1234', email: '[email protected]'});
console.log(Object.keys(sergio));

This works for "classes" old fashion but also for modern classes:

class Pessoa {
  constructor() {
    this.nome = arguments[0].nome || '';
    this.telefone = arguments[0].telefone || '';
    // ... n parâmetros ...
    this.email = arguments[0].email || '';
  }
};

var sergio = new Pessoa({
  nome: 'sergio',
  telefone: '1234',
  email: '[email protected]'
});
console.log(Object.keys(sergio));

I think that's what you were looking for. If what you are looking for is the properties that are defined at instantiation moment of the object, this is more complex, you would have to use getters and setters with some kind of memory that could indicate when they were set.     

27.01.2017 / 16:42