TLDR; 如何直接调用对象父类的 setter 而无需在父类和子类之外调用子类的 setter?
我知道如果存在解决方案,它可能会非常 hacky/magic-like,但我不介意。场景如下:
-
Parent
是来自第 3 方库的类,所以我根本无法更改此代码。 -
Child
是我的代码库中的一个类,但我想将魔术代码保留在它之外,如Prop
类可以与不同的“Child
”类一起使用。 -
Prop
是魔术代码可能驻留的类。
我需要访问 Parent
x
的二传手通过 Child
对象而不调用 x
的 setter 的 Child
.
有可能吗?
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;
}
}
关于javascript - 如何直接调用对象父类的setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403833/