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'
 },
};
2

4 Answers 4

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.

1

Try this

    var person = {
     basic: {
       name: 'jack',
       sex: 0
     }
   };
    person.profile= {
       AA:person.basic.name + '_sth'
    };
1
  • @pvorb initially I forgot to replace collon with equal.
    – Anoop
    May 20, 2013 at 8:54
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

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.