kpozin kpozin - 4 months ago 7x
Javascript Question

Self-references in object literal declarations

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
doesn't refer to
. But is there any way to have values in an object literal's properties depend on other properties declared earlier?


You could do something like:

var foo = {
   a: 5,
   b: 6,
   init: function() {
       this.c = this.a + this.b;
       return this;

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.