Possible Duplicate:
Self-references in object literal declarations
I have an object literal which is used as a configuration element and is looked up for keys.
customRendering:{
key1: func(){....},
key2: func(){....}
}
I have a situation where key2
and key3
can use the same function. Is there a way to assign the same function to both key2
and key3
without having to declare the function outside the object literal and without having to declare an extra key?
I was hoping I could do something like:
key2: key3: func(){....}
I think this part makes it impossible. However, while I use JavaScript all the time, I am not a professional JS ninja, so perhaps I am wrong.
Code for how I would do this (although it seems you already know you can do this, I thought it might be best to say it anyway):
Sorry I understood your question incorrectly.
Here is a possible solution:
Define the function aside from the object:
A safe way:
I don't know what I was thinking earlier. If you're fine with using a more verbose "literal" you can instantiate a custom function:
This is a dirty nasty hack:
you could use a temporary variable to store the reference to the function while setting the object. Be careful to use a closure and to call
var
before using it so that you don't pollute the global namespace:The reason I'm calling this a dirty nasty hack is that it makes the code less readable, it's harder to tell examining this code (especially if the object literal declaration was longer) where
baz
was set.Better to just write the alias outside the object literal so that it's explicitly visible that it is an alias.
Note: the named function format doesn't work:
There's no way within an object literal to define an alias using a shared reference.You can use an aliasing function, but it wont be an identical reference:
The typical way to share a reference is after the object literal, which sounds like what you wanted to avoid:
Alternatively as you pointed out in your question (and for completeness) you could define the function outside of the object literal:
In response to @Peter about returning an object from a function
Using a self-executing anonymous function is another way of instantiating an object inline, and would make this entire question moot:
Or like this: