Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 712
rlemon Avatar asked Sep 15 '11 15:09

rlemon


1 Answers

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);
like image 165
Skylar Anderson Avatar answered Nov 15 '22 19:11

Skylar Anderson