[英]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.