Search code examples
javascriptanonymous-functionobject-properties

Can I have one anonymous function as the value of two different properties in the same object?


Notice in the example below that both create and update are identical. I believe it is possible to have update just be an alias to create's code without needing to write it out a second time.

this.VAROPS = {
    // variable operations
    create:     function(id, value) { variables[id] = value; }
,   delete:     function(id)        { delete variables[id]; }
,   update:     function(id, value) { variables[id] = value; }
};

Solution

  • You can, and you have two options:

    1. Create an actual named function (which might be a local reference inside your scope) and assign it to both properties

      function foo() {}
      var bar = {
          baz: foo,
          xyzzy: foo
      }
      
    2. Assign the first property's value to the second property outside of the object-literal definition

      var foo = {
          bar: function() {}
      }
      foo.baz = foo.bar;