从对象 setter 访问父“this”
Accessing parent `this` from object setter
如何从对象中的 setter 访问父上下文?
在下面的示例中,假设我需要变量 Foo.other
来计算 state.bar
setter。你将如何实现这一目标?
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
returns 指向当前对象的指针。您可以将该引用存储在一个变量中,然后在范围更改时使用该变量检索旧的 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';
在 setter 中调用 this
,您引用的 state
对象没有定义 other
属性(检查第二个 console.log 指的是 this._bar
).
您可以像这样将 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'
如何从对象中的 setter 访问父上下文?
在下面的示例中,假设我需要变量 Foo.other
来计算 state.bar
setter。你将如何实现这一目标?
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
returns 指向当前对象的指针。您可以将该引用存储在一个变量中,然后在范围更改时使用该变量检索旧的 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';
在 setter 中调用 this
,您引用的 state
对象没有定义 other
属性(检查第二个 console.log 指的是 this._bar
).
您可以像这样将 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'