0

I want to create an object in which the class uses the data of two other classes of the same object.

const MatchReplace = {
    Username: {
        RegExp: new RegExp('%USERNAME%', 'g'), // Joined user name
        Value: 'DareFox'
    },
    UserWithTag: {
        RegExp: new RegExp('%USERWITHTAG%', 'g'), // User#XXXX
        Value: 'DareFox#0100'
    },
    ServerName: {
        RegExp: new RegExp('%SERVERNAME%', 'g'), // Name of this server
        Value: 'StackOverflow'
    },
    MemberCount: {
        RegExp: new RegExp('%MEMBERCOUNT%', 'g'), // Member count (human & bots)
        Value: '1005'
    },
    HumanCount: {
        RegExp: new RegExp('%HUMANCOUNT%', 'g'), // Only human count
        Value: '1000'
    },
    BotCount: {
        RegExp: new RegExp('%BOTCOUNT%', 'g'), // Only bot count
        Value: MatchReplace.MemberCount.Value - MatchReplace.HumanCount.Value // Expected: 5
    }
}

But I get an error:

Value: MatchReplace.MemberCount.Value - MatchReplace.HumanCount.Value
               ^

ReferenceError: Cannot access 'MatchReplace' before initialization

Why does this not work and how to make it work?

DareFox
  • 3
  • 1
  • 1
    The best you can is to put '1005' in a variable before and use it two times in your initialization. – Arcord Jun 18 '20 at 08:13
  • *"Why does this not work and how to make it work?"* See [Self-references in object literals / initializers](https://stackoverflow.com/q/4616202/218196) . – Felix Kling Jun 18 '20 at 08:15

1 Answers1

1

It doesn't work because when you create the object JS initializes every property and that cant be done since the object is not still initialized and you have a reference to it in one of its properties.

You can proceed in three ways:

  1. Define the values before the object.
  2. Initialize the object and then assign its properties one by one in the right order.
  3. Define the value using a function or a getter:
const matchReplace = {
 //...
 BotCount: {
       RegExp: new RegExp('%BOTCOUNT%', 'g'), // Only bot count
       get Value() {return MatchReplace.MemberCount.Value - MatchReplace.HumanCount.Value; } // Expected: 5
   }
}
Isidrok
  • 2,015
  • 10
  • 15
  • BTW it works because the property will be read when you access the value instead of when it gets initialized – Isidrok Jun 18 '20 at 08:30