簡體   English   中英

如何在ES6或更高版本的子對象獲取器中捕獲父類“ this”?

[英]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; }
    };
  }
}

valuechild是在構造函數中定義的, 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); 

如果需要在Testvalue ,則始終可以通過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM