Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference the same Object's properties during its creation? [duplicate]

I'm trying to do someting like

o = {   a: { foo: 42 },   b: o.a } 

But that returns an error saying o is not defined. I know I can later do o.b = o.a. But I'm wondering if it's possible to define b while I'm in defining o.

like image 461
fent Avatar asked Jul 26 '11 00:07

fent


People also ask

How is an object property referenced?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

How do you know if two objects have the same reference?

For reference type like objects, == or === operators check its reference only. here a==b will be false as reference of both variables are different though their content are same. and if i check now a==b then it will be true , since reference of both variable are same now.


1 Answers

This is ancient history now, but I just learned about getters and setters, which are perfect for your situation, and I'm sure people looking at this issue could get some value from it..

o = {   a: { foo: 42 },   get b() {     return this.a     }   }  console.log(o.b) // => { foo: 42 } 
like image 110
ignarukih Avatar answered Sep 20 '22 02:09

ignarukih