如何直接调用object的parentclass的setter?

How to directly call setter of an object's parent class?

TLDR; 如何直接调用 object 的 setter 的 parent class 而无需调用 child 的 setter 在 parent 和 child 之外 class?


我知道如果解决方案存在,它可能非常 hacky/magic-like,但我不介意。场景如下:

我需要通过 Child object 访问 Parentx 的 setter,而不调用 setter 的 xChild.

有可能吗?

class Parent {
  constructor() {
    this._x = 255;
  }
  set x(v) {
    console.log("Calling Parent setter");
    this._x = v;
  }
  get x() {
    console.log("Calling Parent getter");
    return this._x;
  }
}

class Child extends Parent {
  constructor() {
    super();
    this.prop = new Prop(this);
  }

  set x(v) {
    console.log("AVOID! Calling Child setter");
    super.x = v;
    // Shennanigans I don't want to run
  }

  get x() {
    console.log("Calling Child getter");
    return super.x;
  }
}

class Prop {
  constructor(child) {
    this.child = child;
  }
  setX() {
    const parent = this.child; // Not sure what to do here.
    const old = parent.x;
    parent.x = 0;
    console.log(`parent.x changed from ${old} to ${parent.x}`);
  }
}

const child = new Child();
child.prop.setX();

Reflect.set 来救你了!它确实允许单独传递接收器:

setX() {
  Reflect.set(Parent.prototype, "x", 0, this.child); // invokes the Parent.protype.x setter
}

备选方案是 Object.getOwnPropertyDescriptor(Parent.prototype, "x").set.call(this.child, 0) 或只是 this.child._x = 0(如果您不需要 运行 setter 代码)。


因此,虽然有可能,但我建议您重新考虑您的设计。也许继承在这里是错误的方法,你应该使用组合而不是 extends Parent:

class Child {
  constructor() {
    this.val = new Parent();
  }

  set x(v) {
    … // Shenanigans
    this.val.x = v;
  }

  get x() {
    return this.val.x;
  }

  // (without the Prop helper class for simplicity)
  setX(v) {
    // without shenanigans
    this.val.x = v;
  }
}