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'
},
};
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'
},
};
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.
Try this
var person = {
basic: {
name: 'jack',
sex: 0
}
};
person.profile= {
AA:person.basic.name + '_sth'
};
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