[英]How to search both parent and child object in Javascript/Lodash/ES6?
[英]How to capture parent class 'this' in a child object getter in ES6 or later?
这是一个简单的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());
输出:
undefined
1
在子对象child
,我要使getter get value()
产生与lambda getValue()
相同的值,即正确捕获父对象的this
并产生1
而不是undefined
。
在class
有没有一种优雅的方法? 还是我应该使用lambda并放弃使用吸气剂?
我可能可以这样做:
this.child = {
parent: this,
get value() { return this.parent._value; },
};
但是我不想公开child.parent
,只child.value
。
对自己说,可以通过在constructor
内部捕获this
来完成:
class Test {
constructor(val) {
const self = this;
this._value = val;
this.child = {
get value() { return self._value; }
};
}
}
value
和child
是在构造函数中定义的, value
应该是私有的,并且只能通过child
访问。 您可以在闭包中将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);
如果需要在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.