Home  >  Q&A  >  body text

Self-references in object literals/initializers

<p>Is there any way to make something like the following work in JavaScript? </p> <pre class="brush:php;toolbar:false;">var foo = { a: 5, b: 6, c: this.a this.b // Doesn't work };</pre> <p>In its current form, this code obviously throws a reference error because <code>this</code> does not reference <code>foo</code>. But<em>yes</em>Is there any way to make the value in an object literal property dependent on other previously declared properties? </p>
P粉921130067P粉921130067441 days ago452

reply all(2)I'll reply

  • P粉615829742

    P粉6158297422023-08-30 11:54:25

    You can do this:

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

    This will be some kind of one-time initialization of the object.

    Note that you are actually assigning the return value of init() to foo, so you must return that value .

    reply
    0
  • P粉322319601
  • Cancelreply