Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reference other properties during object declaration in JavaScript? [duplicate]

Tags:

javascript

I am trying to do something like this:

var obj = {     a: 5,     b: this.a + 1 } 

(instead of 5 there is a function which I don't want to execute twice that returns a number)

I can rewrite it to assign obj.b later from obj.a, but can I do it right away during declaration?

like image 802
serg Avatar asked Jan 06 '11 18:01

serg


People also ask

How do you copy properties from one object to another in JavaScript?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Does JavaScript copy object by reference?

Objects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory. Passed by reference.

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

You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.


2 Answers

No. this in JavaScript does not work like you think it does. this in this case refers to the global object.

There are only 3 cases in which the value this gets set:

The Function Case

foo(); 

Here this will refer to the global object.

The Method Case

test.foo();  

In this example this will refer to test.

The Constructor Case

new foo();  

A function call that's preceded by the new keyword acts as a constructor. Inside the function this will refer to a newly created Object.

Everywhere else, this refers to the global object.

like image 124
Ivo Wetzel Avatar answered Sep 23 '22 02:09

Ivo Wetzel


There are several ways to accomplish this; this is what I would use:

function Obj() {     this.a = 5;     this.b = this.a + 1;     // return this; // commented out because this happens automatically }  var o = new Obj(); o.b; // === 6 
like image 22
ken Avatar answered Sep 22 '22 02:09

ken