2

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
Justin Bull
  • 7,785
  • 6
  • 26
  • 30

3 Answers3

7

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;
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • Perfect thanks. I actually resorted to this method. I was just hoping my above mentioned method would work. Guess not! – Justin Bull Dec 11 '09 at 18:50
1

Or:

var myVar = "test";

var myArr = {
    var1: myVar,
    var2: myVar
}
Jay Zeng
  • 1,423
  • 10
  • 10
  • I am trying to keep all variables inside a single object for name-space reasons. This does not work in my situation. – Justin Bull Dec 11 '09 at 19:38
  • 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 Dec 11 '09 at 19:53
  • 1
    What array? There are no arrays being used here. – Justin Johnson Dec 12 '09 at 07:56
-1
var myVars = {
    var1: "test",
    var2: this.var1
};

perhaps?

matpol
  • 3,042
  • 1
  • 15
  • 18