I want to set two proper开发者_运维技巧ties 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?
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).
You can declare the function first and use it with a
& c
:
function f() { ... }
var obj = {
a: f,
b: alert,
c: f
};
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.
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() { ... };
精彩评论