从对象设置器访问parent`this“



如何从对象中的setter访问父上下文?

在下面的示例中,想象一下我需要变量Foo.other来计算state.bar设置器。您将如何实现这一目标?

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'

this返回指向当前对象的指针。您可以将该引用存储在变量中,然后在更改范围时使用该变量来检索旧的this对象。此类变量的最常见名称是self_this_selfme_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';

在设置器内调用 this,您参考未定义的other属性的state对象(请检查第二个Console.log,涉及this._bar(。

(。

您可以将this存储到这样的变量(self(:

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'

最新更新