Define property based on others during object creation

Asked

Viewed 61 times

3

I am making an attempt to 'name' popular 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 full name variable in the initial definition of var 'person'?

2 answers

7

You have to do it in steps.
When you want to use nome + sobrenome the object is not yet closed and these properties do not yet exist. Anyway it would not be possible to call them that. So Javascript thinks they are variables.

Use like 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: http://jsfiddle.net/3epeLuzL/

5


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

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

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

I make available here a Example jsfiddle.

Browser other questions tagged

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