0

Could we not initialize a Javascript object's property with value of another property of the same object?

I tried as in the code below and seems the initialization stays undefined:

"use strict"
let obj = {
  name1 : 'Me',
  name2 : this.name1,
  func1(){
   return name2;
  },
};
console.log(obj.name2); //=> undefined
console.log(obj.func1()); //=> ReferenceError: name2 is not defined
Saptadeep
  • 327
  • 1
  • 3
  • 13
  • 3
    is `name2 : this.name,` supposed to be `name2 : this.name1,` ? – Nick Parsons Jan 14 '21 at 09:59
  • @NickParsons That was a last minute typo! Apologies. Does not work even with 'name1'. Correcting. – Saptadeep Jan 14 '21 at 11:50
  • 1
    See the linked dup, it shows you how to do what you're after with getters: [Self-references in object literals / initializers](https://stackoverflow.com/q/4616202), in the case of `func1()`, you need to use `this.name2` (provided that name2 has a valid value) – Nick Parsons Jan 14 '21 at 11:55

0 Answers0