views:

131

answers:

3

I have an array of variables. And I want one variable to equal the previous one. For example:

var myVars = {
    var1: "test",
    var2: var1
};

alert(myVars.var2);

//output: var1 is not defined

Any thoughts? I'm sure this is some sort of variable scope limitation. I would like to hear otherwise. Thanks in advance.

+6  A: 

You cannot refer to the same object literal in an expression without using a function, I would recommend you to use the equivalent syntax:

var myVars = {};

myVars.var1 = "test",
myVars.var2 = myVars.var1;
CMS
Perfect thanks.I actually resorted to this method.I was just hoping my above mentioned method would work.Guess not!
Jabes88
A: 
var myVars = {
    var1: "test",
    var2: this.var1
};

perhaps?

matpol
`this` is bound to the function-context, has nothing to do with the `myVars` instance
CMS
+1  A: 

Or:

var myVar = "test";

var myArr = {
    var1: myVar,
    var2: myVar
}
Jay Zeng
I am trying to keep all variables inside a single object for name-space reasons. This does not work in my situation.
Jabes88
Right in that case you need to wrap all necessary variables in an object, like what CMS suggested. Just a note that you can also declare the array as object:var myVars = new Object();myVars.var1 = "test";myVars.var2 = myVars.var1;
Jay Zeng
What array? There are no arrays being used here.
Justin Johnson