Search code examples
javascriptdependenciesobject-literal

Is it possible to initialize an object with the literal notation if there are dependencies among its members?


Suppose I have an object like this

a = {b = function() { return 1 }, c: 2, f: 3}
a.z = a.b()

Is there a way to write it in a single assignment of object literal notation? Similar to:

a = {b: function() { return 1 }, c: 2, f: 3, z: this.b()}

Obviously this won't work because this is still bound to the scope that is defining the object, not the object itself. a.b() doesn't work either because a is not defined yet.

I'm actually using CoffeeScript but I'm pretty sure that if there is a clever way of doing this in plain JavaScript, it's going to look shorter and more "functional" in CoffeeScript as well.


Solution

  • you can take advantage of JS's leaky assignments to memorize the value of the property to another variable from within the object literal:

    a = { b: b = function() { return 1 }, c: 2, f: 3, z: b() };
    

    note that as shown, b is a global, so you should likely use something like "var b, a=" (rest of code as shown) to prevent leakage.