0

I'm creating an object using literal notation. Is it possible to have some of the properties use previously defined properties as their value?

For example:

    var test = {
        prop1: obj1, 
        prop2: obj2,
        prop3: (prop1!=null)?prop1:prop2
    };
1
  • 1
    could you please be more specific? From your example I don't really see what the nature of the question is, because you should be able to test it out fairly easily. Is there a more detailed example you inted to be showing? Commented Feb 28, 2012 at 20:35

3 Answers 3

1

If you are trying to do something like var x = { 'a': 1, 'b': x.a } then it won't work. Since x is not finished being defined.

But you can do something like

var
    a = 12,
    b = 24,
    c = a + b; // 36

This is because each var definition is interpreted sequentially. Basically equivalent to

var a = 12;
var b = 24;
var c = a + b;

But with objects and arrays the entire definition is interpreted one time.

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

Comments

1

No and yes.

The following aren't possible:

var o = {
    a : 42,
    b : o.a //raises a TypeError, o is not defined
};

var o = {
    a : b : 42 //raises a SyntaxError, unexpected :
};

The following, however, are:

//referencing a pre-existing variable is obviously possible
var ans = 42;
var o = {
    a : ans,
    b : ans
};

var o = {
    a : 42
};
//after the variable has been declared, you can access it as usual
o.b = o.a;

If you feel limited by the value being a single statement, you can always use an anonymous function:

var o = {
    a : (function () {
        doStuff();
        return otherStuff();
    }())
};

Comments

0

to keep your example:

var test = {
  prop1: obj1,
  prop2: obj2,
  prop3: (function () {
    return (test.prop1!=null)?test.prop1:test.prop2;
  })()
};

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.