0

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'
 },
};
nfpyfzyf
  • 2,891
  • 6
  • 26
  • 30
  • possible duplicate of [reference variable in object literal?](http://stackoverflow.com/questions/4858931/reference-variable-in-object-literal) – Quentin May 20 '13 at 08:48
  • You cannot have a comma before closing an object literal: `, }' is not allowed. – pvorb May 20 '13 at 09:05

4 Answers4

3

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.

Community
  • 1
  • 1
pvorb
  • 7,157
  • 7
  • 47
  • 74
1

Try this

    var person = {
     basic: {
       name: 'jack',
       sex: 0
     }
   };
    person.profile= {
       AA:person.basic.name + '_sth'
    };
Anoop
  • 23,044
  • 10
  • 62
  • 76
0

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

nl-x
  • 11,762
  • 7
  • 33
  • 61
0

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');
KooiInc
  • 119,216
  • 31
  • 141
  • 177