如何从对象中的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
,_self
,me
和_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'