Search code examples
javascriptobjectthisgetter-setter

Accessing parent `this` from object setter


How can you access a parent context from a setter in an object?

In the following example, imagine I need the variable Foo.other to compute the state.bar setter. How would you go about achieving that?

class Foo {
    constructor() {
        this.other = 'i am an other variable'
        this.state = {
            _bar: 'default',
            set bar(flag) {
                console.log() // how can I access foo.other from here?
                this._bar = flag
            },
            get bar() {
                return this._bar
            }
        }
    }
}

const foo = new Foo()
foo.state.bar = 'yolo'

Solution

  • this returns a pointer to the current object. You can store that reference in a variable and then use that variable to retrieve the old this object when the scope has been changed. Most common names for such variables are self, _this, _self, me and _me.

    class Foo {
      constructor() {
        var self = this;
        this.other = 'i am an other variable';
        this.state = {
          _bar: 'default',
          set bar(flag) {
            console.log(self.other);
            this._bar = flag;
          },
          get bar() {
            return this._bar;
          }
        }
      }
    }
    
    const foo = new Foo();
    foo.state.bar = 'yolo';