Q: 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'


A: 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';



A: Calling this inside the setter, you refer to the state object that does not have an other property defined (Check the second console.log that refers to this._bar).
You can store this to a variable (self) like this:


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

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


