Is there any way to get something like the following to work in JavaScript?
var foo = {
a: 5,
b: 6,
c: this.a + this.b // Doesn't work
};
In the current form, this code obviously throws a reference error since this
doesn't refer to foo
. But is there any way to have values in an object literal's properties depend on other properties declared earlier?
just for the sake of thought - place object's properties out of a timeline:
there are better answers above too. This is how I modified example code you questioned with.
UPDATE:
The obvious, simple answer is missing, so for completeness:
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:
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:
Or of course, if you need to do this more than once:
then where you need to use it:
How about this solution this will work with nested objects with array as well
A different approach, to keep things a bit simpler and not define new functions in the object, is to keep the original object with its properties, create a second object with the dynamic properties that use the first object's properties and then merge using spread.
So:
Object
Object 2
Merge
or
Result of foo:
All within the same js, no new functions within the object, only using assign or spread.
Other approach would be to declare the object first before assigning properties into it:
With that, you can use the object variable name to access the already assigned values.
Best for
config.js
file.Now in ES6 you can create lazy cached properties. On first use the property evaluates once to become a normal static property. Result: The second time the math function overhead is skipped.
The magic is in the getter.
In the arrow getter
this
picks up the surrounding lexical scope.