0

I have a class like the following.

class ColorTest {

    #light;

    constructor() {

        this.#light = {
            color: "Purple", 
            brightness: "Bright", 
        }
        this.colors = {
            first: {
                get color() {
                    return this.light.color;
                }, 
                get brightness() {
                    return this.light.brightness;
                }
            }, 
            second: {
                color: "", 
                brightness: ""
            }
        }
    }

    get light() { 
        return this.#light; 
    }
    set light(value) {
        // Do stuff
    }
}

let colorTest = ColorTest();
let firstColor = colorTest.colors.first.color;

When I try to run this code it gives me an error message that says "TypeError: Cannot read property 'color' of undefined", with a reference to the line that says return this.light.color;. No matter what I try, I cannot figure out how to get around this. Any suggestions?

Robin
  • 75
  • 1
  • 5
  • That's what I'm suspecting too. But how to I get a reference to the `this` of the class? – Robin Jul 19 '22 at 19:42
  • Why not simply do `this.colors = {first: this.light, second: {…}};`? – Bergi Jul 19 '22 at 21:28
  • 1
    `this` inside the getter refers (usually) to the object it was accessed on, that is `colorTest.colors.first`. That object doesn't have a `.light` property. You can either add one (to reference `this.#light`), or not use `this`. Use the old [`const that = this;` approach](https://stackoverflow.com/q/20279484/1048572). Or even easier, `const light = this.#light = {…};` and then refer to `light` directly. – Bergi Jul 19 '22 at 21:30

0 Answers0