Set property based on others during object creation

3

I am making a popular 'fullname' attempt with the result of the first two variables, but without success.

var pessoa = { nome: "Joao", sobrenome: "Silva", nomecompleto : nome + sobrenome };

alert(pessoa.nomecompleto);
  

Uncaught ReferenceError: Name is not defined

Is there any way to get the expected result of the variable 'fullname' in the initial definition of var 'person'?

    
asked by anonymous 24.09.2014 / 19:31

2 answers

5

As explained by @Sergio, the object is not yet built into memory and therefore there is no pointer to its content yet.

If it is really necessary to declare the nome_completo attribute within this literal object ( { ... } ), for example: if you want, when updating nome , nome_completo is automatically "updated" together , the closest you can do is to transform nome_completo into a method:

var pessoa = { nome: "Rui", sobrenome: "Pimentel", getNomeCompleto: function(){
    return this.nome + " " + this.sobrenome;
}};

Make a example JSFiddle here.

    
24.09.2014 / 19:48
7

You have to do this in steps. When you want to use nome + sobrenome the object is not yet defined and these properties do not yet exist. In any case, it would not be possible to call them that. This way JavaScript thinks they are variables.

Use this:

var pessoa = { nome: "Joao", sobrenome: "Silva" };
pessoa.nomecompleto = pessoa.nome + pessoa.sobrenome
alert(pessoa.nomecompleto);

You can however make a Class and use:

function Pessoa(nome, sobrenome) {
    this.nome= nome;
    this.sobrenome= sobrenome;
    this.nomeCompleto = this.nome + ', ' + this.sobrenome;
}

var novaPessoa = new Pessoa('Luis', 'Martins');
console.log(novaPessoa .nomeCompleto); // vai dar "Luis, Martins"

Example: link

    
24.09.2014 / 19:35