开发者

JavaScript Object Literal Notation Internal Variable Pointing [duplicate]

开发者 https://www.devze.com 2022-12-14 06:35 出处:网络
This question already has answers here: Self-references in object literals / initializers (30 answers) 开发者_如何学编程
This question already has answers here: Self-references in object literals / initializers (30 answers) 开发者_如何学编程 Closed 8 years ago.

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.


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;


Or:

var myVar = "test";

var myArr = {
    var1: myVar,
    var2: myVar
}


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

perhaps?

0

精彩评论

暂无评论...
验证码 换一张
取 消