Is there a better title for this?
Okay, is something like this legal?
var myobj = {
key1: "val开发者_如何学编程1",
key2: this.key1
};
I haven't tried it, but I'm looking for a way to have identical values for separate keys in an object, preferably in a concise way.
Your code is legal but doesn't do what you mean. When evaluating the key:...
part this
is not bound to the yet-non-existent object, but to the context where myobj is being built. You have to store the value in a variable and then using the variable... like:
var kv = "val1";
var myobj = {
key1: kv,
key2: kv
};
note that here you're not creating a closure if this is your fear. That only happens for function
expressions
try:
var myobj = {};
myobj['key2'] = (myobj['key1'] = 'val1');
Since in javascript, value assignment also returns the value as well, so you can be somewhat concise.
精彩评论