8

I want to set two properties equal to each other in one object. Here's an example:

var obj = { // I want to do something like this
    a: function() { ... },
    b: alert,
    c: a
};

Obviously that doesn't work and I have to do something like this:

var obj = {
    a: function() { ... },
    b: alert,
};
obj.c = obj.a;

Is there any way to do that in the declaration?

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • See http://stackoverflow.com/questions/2787245/how-can-a-javascript-object-refer-to-values-in-itself, http://stackoverflow.com/questions/4618541/can-i-reference-other-properties-during-object-declaration-in-javascript, and http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations – Crescent Fresh May 12 '11 at 00:43

4 Answers4

1

You can declare the function first and use it with a & c:

function f() { ... }

var obj = {
    a: f,
    b: alert,
    c: f
};
manji
  • 47,442
  • 5
  • 96
  • 103
1

You can put the value into a separate variable:

var temp = function() { ... };
var obj = { // I want to do something like this
    a: temp,
    b: alert,
    c: temp
};

However, you cannot do any better than that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

If you want to do everything inside the object initializer, then you can have one property call the function from the other and relay any arguments using the Function.arguments property:

var obj = { 
    a: function() { ... },
    b: alert,
    c: function() { return this.a(arguments); }
};

However, your best bet might be to create a variable containing the anonymous function first, then assign its value to both properties in your object initializer:

var fn = function() { ... };
var obj = {
    a: fn,
    b: alert,
    c: fn
};

You can also do something like this, but I'd go with the approach one above:

var obj = { b: alert };
obj.a = obj.c = function() { ... };
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
1
var obj = { 
    a: function() { alert("hello")},
    b: alert,
    c: function(){return this.a()}
};

obj.c();

As SLaks mentioned, this won't work if the functions have properties (eg, prototype or arguments.callee).

Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44
  • 1
    This won't work if the functions have properties (eg, `prototype` or `arguments.callee`). – SLaks May 12 '11 at 00:50