Safe way:
I do not know what I was thinking before. If you find it convenient to use a more verbose literal, you can create a custom function:
o = new function () { this.foo = function () { console.log('works'); }; this.bar = this.foo; };
This is a dirty nasty hack:
You can use a temporary variable to store a function reference when setting the object. Be careful to use closure and invoke var before using it so that you don't pollute the global namespace:
(function () { var o, baz; o = { foo: baz = function () {console.log('works')}, bar: baz }
The reason I call it a dirty nasty hack is because the code makes it less readable, itβs more difficult to talk about this code (especially if the object literal declaration was larger), where baz was installed.
Itβs better to just write an alias outside the object literal so that it explicitly displays that it is an alias.
Note. the default name format does not work:
o = { //THIS WON'T WORK foo: function baz() {/* code */}, bar: baz }
There is no way in an object literal to define an alias using a generic link.
You can use the aliases function, but it will not be an identical reference:
o = { foo: function... bar: function () { return this.foo() }
A typical way to exchange a link is after an object literal, which sounds like something you wanted to avoid:
o = { foo: function... } o.bar = o.foo;
Alternatively, as you pointed out in your question (and for completeness), you can define a function outside the object literal:
func = function () {}; o = { foo: func, bar: func }
In response to @Peter about returning an object from a function
Using a self-executing anonymous function is another way to instantiate an inline object and will make this whole question moot:
o = (function () { var o = { foo: function () {} } o.bar = o.foo; return o; }());
Or like this:
var o = (function () { var shared = function() { console.log("shared") }; return { foo: shared, bar: shared } }());