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
  • possible duplicate of reference variable in object literal? Commented May 20, 2013 at 8:48
  • You cannot have a comma before closing an object literal: `, }' is not allowed. Commented May 20, 2013 at 9:05

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

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

1 Comment

@pvorb initially I forgot to replace collon with equal.
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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.