kpozin kpozin - 5 months ago 15
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
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?

Answer

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.

Comments