Self-references in object literals / initializers
You could do something like:
var foo = {
a: 5,
b: 6,
init: function() {
this.c = this.a + this.b;
return this;
}
}.init();
This would be some kind of one time initialization of the object.
Note that you are actually assigning the return value of init()
to foo
, therefore you have to return this
.
Well, the only thing that I can tell you about are getter:
var foo = {
a: 5,
b: 6,
get c() {
return this.a + this.b;
}
}
console.log(foo.c) // 11
This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).
The obvious, simple answer is missing, so for completeness:
But is there any way to have values in an object literal's properties depend on other properties declared earlier?
No. All of the solutions here defer it until after the object is created (in various ways) and then assign the third property. The simplest way is to just do this:
var foo = {
a: 5,
b: 6
};
foo.c = foo.a + foo.b;
All others are just more indirect ways to do the same thing. (Felix's is particularly clever, but requires creating and destroying a temporary function, adding complexity; and either leaves an extra property on the object or [if you delete
that property] impacts the performance of subsequent property accesses on that object.)
If you need it to all be within one expression, you can do that without the temporary property:
var foo = function(o) {
o.c = o.a + o.b;
return o;
}({a: 5, b: 6});
Or of course, if you need to do this more than once:
function buildFoo(a, b) {
var o = {a: a, b: b};
o.c = o.a + o.b;
return o;
}
then where you need to use it:
var foo = buildFoo(5, 6);