Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting two properties equal in the declaration

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?

like image 552
qwertymk Avatar asked May 12 '11 00:05

qwertymk


People also ask

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique.

How do you change one property of an object?

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.

How properties are assigned to an object in JavaScript?

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.

How to initialize an object in JavaScript?

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 ( {} ).


3 Answers

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).

like image 121
Kevin Ennis Avatar answered Oct 16 '22 12:10

Kevin Ennis


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

function f() { ... }

var obj = {
    a: f,
    b: alert,
    c: f
};
like image 45
manji Avatar answered Oct 16 '22 13:10

manji


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.

like image 38
SLaks Avatar answered Oct 16 '22 13:10

SLaks