nfpyfzyf
nfpyfzyf

Reputation: 2991

Reference variable in definition?

How can I reference variable while define it in Javascript?

var person = {
 basic: {
   name: 'jack',
   sex: 0,
 },
 profile: {
   AA: 'jack' + '_sth', # How can I write like this: AA: basic.name + '_sth'
 },
};

Upvotes: 0

Views: 78

Answers (4)

KooiInc
KooiInc

Reputation: 122936

You could also use an Immediately Invoked Function Expression (IFFE) :

var person = function(name) {
 var prsn = {
      basic: {
        name: name || 'anonymous',
        sex: 0
       }
      };
 return {basic: prsn.basic, profile: {AA: prsn.basic.name + '_sth'}};
}('Jack');

Upvotes: 0

pvorb
pvorb

Reputation: 7289

You can't.

You have to do

var name = 'jack';

var person = {
 basic: {
   name: name,
   sex: 0
 },
 profile: {
   AA: name + '_sth'
 }
};

Just like this answer says, you could also do something like the following

function Person() {
  this.basic = {
    name: 'jack',
    sex: 0
  };
  this.profile = {
    AA: this.basic.name + '_sth'
  };
}

var person = new Person();

But this creates an instance of Person, not a plain and simple JS object.

Upvotes: 3

nl-x
nl-x

Reputation: 11832

you just cant. other than work arounds like sushil's and pvorb's, you cant reference an object still being defined.

also you can try a getfunction

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Try this

    var person = {
     basic: {
       name: 'jack',
       sex: 0
     }
   };
    person.profile= {
       AA:person.basic.name + '_sth'
    };

Upvotes: 1

Related Questions