Search code examples
javascriptobject-literal

Referring to previously defined properties within an object literal


When using object constructors, properties can be directly assigned to the value of previously defined properties:

var foo = new (function() {
   this.bar = 5;
   this.baz = this.bar;
})();
alert(foo.baz) // 5

I would like to refer to a previously defined property within an OBJECT LITERAL:

var foo = {
   bar : 5,
   baz : bar
}
alert (foo.baz) // I want 5, but evaluates to undefined

I know that I could do this:

var foo = {
   bar : 5,
   baz : function() {
      alert(this.bar); // 5
   }

But I want to assign baz directly to a value rather than a function. Any ideas?


Solution

  • You can also just build a literal by parts:

    var foo = {bar:5};
    foo.baz = foo.bar;
    

    If you need to fit this inside an expression (instead of through multiple statements) you can try abusing the comma operator or you can make a helper function:

    (Warning: untested code)

    function make_fancy_object(base_object, copies_to_make){
         var i, copy_from, copy_to_list;
         for(copy_from in copies_to_make){
             if(copies_to_make.hasOwnProperty(copy_from)){
                 copy_to_list = copies_to_make[copy_from];
                 for(var i=0; i<copy_to_list.length; i++){
                     base_object[copy_to_list[i]] = base_object[copy_from];
                 }
              }
          }
    }
    
    var foo = make_fancy_object(
        {bar: 5},
        {bar: ["baz", "biv"]}
    );
    
    //foo.baz and foo.biv should be 5 now as well.