Object referencing its own property on initialization [duplicate]

Possible Duplicate:
Self-references in object literals / initializers

Can this be done? (obviously not in this syntax)

var a = {
    b : 10,
    c : this.b * 2 // returns 'undefined'
};

I have also tried

var a = {
    b : 10,
    c : a.b * 2 // throws error 'a is undefined'
};

and

var a = {
    b : 10,
    c : b * 2 // throws error 'b is undefined'
};

It makes sense to me that these values are undefined, I have not finished defining them. However it seems to me like there would be a solution to structuring a object like that and having c be conditional on b

Answers:

Answer

Alternatively, you can use a self starting function to give you a similar affect to what you are looking for:

var a = (function() {
    var b = 10;
    return {
        b:b,
        c:b*2
    }
})();

console.log(a.c);
Answer

Not using object literal notation, but you can use functions to create it:

function Structure(value) {
    this.b = value;
    this.c = 2 * value;
}

var a = new Structure(10);

or

function makeStructure(value) {
    return {b:value, c:2*value};
}

var a = makeStructure(10);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.