0
let obj = {
    a:2,
    b: this.a,
};

console.log(obj.a); //outputs 2
console.log(obj.b); //outputs undefined

Why can't I access one property of an object from another property within the same object? What's the way around this?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Gsbansal10
  • 303
  • 5
  • 12
  • 2
    Does this answer your question? [Can I reference other properties during object declaration in JavaScript?](https://stackoverflow.com/questions/4618541/can-i-reference-other-properties-during-object-declaration-in-javascript) – He Wang Mar 07 '20 at 05:15

1 Answers1

1

It's a scope issue. Put the b outside of the object:

let obj = {
   a:2
}

obj.b = obj.a;
console.log(obj.a);
console.log(obj.b);

You can't use a this keyword before you've declared the variable.

Max Voisard
  • 1,685
  • 1
  • 8
  • 18