如何从对象的设置器访问父上下文?
在下面的示例中,假设我需要变量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'
答案 0 :(得分:3)
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';
答案 1 :(得分:1)
在设置器内部调用this
时,将引用未定义state
属性的other
对象(请检查引用this._bar
的第二个console.log )。
您可以像这样将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'