Search code examples
javascriptobject

Initialize object property with use other properties of same object


I am newbie in JS. And my question is: How I can pretty initialize object property with use other properties of same object.

Example:

var obj = {
  par1 : 2*2,
  par2 : this.par1
};

Thanks.


Solution

  • During Object literal declaration you have to use the full reference:

    var myObject = {
        par1 : 2*2,
        par2 : myObject.par1
    };
    

    The this keyword will only work on an instantiated Object.