JavaScript Object Literal Notation Internal Variab

2019-02-27 06:12发布

This question already has an answer here:

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.

3条回答
时光不老,我们不散
2楼-- · 2019-02-27 06:19

Or:

var myVar = "test";

var myArr = {
    var1: myVar,
    var2: myVar
}
查看更多
疯言疯语
3楼-- · 2019-02-27 06:31

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;
查看更多
Viruses.
4楼-- · 2019-02-27 06:32
var myVars = {
    var1: "test",
    var2: this.var1
};

perhaps?

查看更多
登录 后发表回答