Return all constructor parameters of a function in Javascript

Asked

Viewed 135 times

0

Imagine the following situation:

I have several "classes" built from javascript functions where their properties are defined within 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 property arguments[0] is used to send an object with all the properties that will be set for that 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 Javascript, I probably wouldn’t be able to do that natively. Therefore, using a prototyped function, how can I return all parameters defined within my constructor?

2 answers

0

Well from what I realized Voce wants to return all the parameters defined in the constructor, I just didn’t quite realize where the object arguments comes.

We can return the parameters in the 'class'' Pessoa 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
}

0

To know what properties an intuition has you can do like 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 old style "classes" 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 are the properties that are closed at the time of instantiation of the object, that is more complex, you would have to use getters and setters with some type of memory that can indicate when they were set.

Browser other questions tagged

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