kpozin kpozin -5 years ago 122
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download