0

In this simplified code, I want to give someGetters a parameter and to return a specific text, but the getters can't seem to access the parent Object's "this", "this" is pointed to someGetters.

var constants = {
    FLAG2: "testx2",
    FLAG4: "testx4",
    FLAG6: "testx6",
    someGetters: {
        get [this.FLAG2]() { // tried "this" but it points to someGetters
            return "Test Test"
        },
        get [constants.FLAG4]() { // tried constants but it says it's not defined yet
            return "Test Test Test Test"
        },
        get ["testx6"]() { // but this works
            return "Test Test Test Test Test Test"
        }
    }
};

console.log(constants.someGetters[constants.FLAG2]) // expected result: Test Test

Note that constants is exported from another js file called constants.ts.

Ayoub Laazazi
  • 540
  • 7
  • 15
  • See [Self-references in object literals / initializers](/q/4616202/4642212), [How does the "this" keyword in Javascript act within an object literal?](/q/13441307/4642212), [How does the "this" keyword work?](/q/3127429/4642212). – Sebastian Simon Sep 24 '21 at 15:53
  • @SebastianSimon already saw them, not what I need (as this is a case for getter inside object that is inside another object) but thanks. – Ayoub Laazazi Sep 24 '21 at 16:09
  • But the `this` isn’t inside the getter. It’s effectively in global scope. – Sebastian Simon Sep 24 '21 at 16:16

1 Answers1

2

You can't refer to the object's properties until you've finished constructing it. So add someGetters after you've assigned constants, and then refer to constants rather than this.

var constants = {
  FLAG2: "testx2",
  FLAG4: "testx4",
  FLAG6: "testx6",
};

constants.someGetters = {
  get [constants.FLAG2]() {
    return "Test Test"
  },
  get [constants.FLAG4]() {
    return "Test Test Test Test"
  },
  get ["testx6"]() { // but this works
    return "Test Test Test Test Test Test"
  }
}

console.log(constants);
Barmar
  • 741,623
  • 53
  • 500
  • 612