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?
if your object is written as a function which returns an object, AND you use ES6 object-attribute 'methods', then it's possible:
You could do something like:
This would be some kind of one time initialization of the object.
Note that you are actually assigning the return value of
init()
tofoo
, therefore you have toreturn this
.Simply instantiate an anonymous function:
I use the following code as alternative, and it works. And the variable can be array too. (@ Fausto R.)
Here were using class expressions to get the nested object literal interface we'd want. This is the next best thing IMHO to being able to reference the properties of an object during creation.
Main thing to note is while using this solution, you have exact same interface as you'd have had from an object literal. And the syntax is pretty close to an object literal itself (vs using a function, etc).
Compare the following
Solution I've proposed
Solution if object literals would've sufficed
Another example
Here in this class, you can combine multiple relative path among themselves, which is not possible with an object literal.
You can do it using the module pattern. Just like:
With this pattern you can instantiate several foo objects according to your need.
http://jsfiddle.net/jPNxY/1/