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?
You cannot. Property keys are unique.
After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With