[英]How to capture parent class 'this' in a child object getter in ES6 or later?
Here is a simple JavaScript code: 这是一个简单的JavaScript代码:
class Test {
constructor(val) {
this._value = val;
this.child = {
get value() { return this._value; },
getValue: () => { return this._value; }
};
}
}
let o = new Test(1);
console.log(o.child.value);
console.log(o.child.getValue());
The output: 输出:
undefined
1
In the child object child
, I want to make the getter get value()
to produce the same value as the lambda getValue()
, ie to capture the parent's this
properly and produce 1
rather than undefined
. 在子对象
child
,我要使getter get value()
产生与lambda getValue()
相同的值,即正确捕获父对象的this
并产生1
而不是undefined
。
Is there an elegant way of doing it within the class
? 在
class
有没有一种优雅的方法? Or should I use the lambda and give up on the getter? 还是我应该使用lambda并放弃使用吸气剂?
I could probably do this: 我可能可以这样做:
this.child = {
parent: this,
get value() { return this.parent._value; },
};
However I don't want to expose child.parent
, only child.value
. 但是我不想公开
child.parent
,只child.value
。
Answering to myself, it can simply be done by capturing this
inside constructor
: 对自己说,可以通过在
constructor
内部捕获this
来完成:
class Test {
constructor(val) {
const self = this;
this._value = val;
this.child = {
get value() { return self._value; }
};
}
}
The value
and child
are defined in the constructor, and value
should be private, and accessed only via child
. value
和child
是在构造函数中定义的, value
应该是私有的,并且只能通过child
访问。 You can set value
as a normal variable in the closure, and access it via the child
getter and setter: 您可以在闭包中将
value
设置为普通变量,并通过child
getter和setter访问它:
class Test { constructor(val) { let value = val; this.child = { get value() { return value; }, set value(v) { value = v; }, }; } } let o = new Test(1); console.log(o.child.value); o.child.value = 5; console.log(o.child.value);
If you need the value
inside Test
, you can always access it via the child
: 如果需要在
Test
该value
,则始终可以通过child
访问它:
class Test { constructor(val) { let value = val; this.child = { get value() { return value; }, set value(v) { value = v; }, }; } get value() { return this.child.value; } set value(v) { this.child.value = v; } } let o = new Test(1); console.log(o.value); o.value = 5; console.log(o.value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.