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:
o = new function () {
this.foo = function () { console.log('works'); };
this.bar = this.foo;
};
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:
(function () {
var o, baz;
o = {
foo: baz = function () {console.log('works')},
bar: baz
}
//more code
}());
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:
o = { //THIS WON'T WORK
foo: function baz() {/* code */},
bar: baz
}
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:
o = {
foo: function...
bar: function () { return this.foo() } //even better if you use `apply` or `call`
}
The typical way to share a reference is after the object literal, which sounds like what you wanted to avoid:
o = {
foo: function...
}
o.bar = o.foo;
Alternatively as you pointed out in your question (and for completeness) you could define the function outside of the object literal:
func = function () {/* code */};
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 of instantiating an object inline, and would make this entire question moot:
o = (function () {
var o = {
foo: function () {/*code*/}
}
o.bar = o.foo;
return o;
}());
Or like this:
var o = (function () {
var shared = function() { console.log("shared") };
return {
foo: shared,
bar: shared
}
}());