简体   繁体   English

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

[英]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 . valuechild是在构造函数中定义的, 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 : 如果需要在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