Reputation: 858
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
.
Upvotes: 0
Views: 37
Reputation: 781088
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);
Upvotes: 2