代码之家  ›  专栏  ›  技术社区  ›  avo

如何在ES6或更高版本的子对象getter中捕获父类“this”?

  •  0
  • avo  · 技术社区  · 7 年前

    下面是一个简单的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 ,我想做一个吸气剂 get value() 产生与lambda相同的值 getValue() ,即捕获父对象的 this 1 而不是 undefined .

    有没有一个优雅的方式做这件事 class ? 或者我应该使用lambda而放弃getter?

    我可以这样做:

        this.child = {
          parent: this, 
          get value() { return this.parent._value; },
        };
    

    但是我不想暴露 child.parent child.value .

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ori Drori    7 年前

    这个 value child 价值 应该是私有的,并且只能通过 小孩 . 你可以设置 价值 作为闭包中的正常变量,并通过 小孩

    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 小孩 :

    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);
        2
  •  1
  •   avo    7 年前

    回答我自己,这可以简单地通过捕捉 this 里面 constructor :

    class Test {
      constructor(val) {
        const self = this;
        this._value = val;
        this.child = {
          get value() { return self._value; }
        };
      }
    }