首页 > 解决方案 > 如何在Javascript中调用祖父母类的setter

问题描述

想象一下,我有 3 个类ChildParent并按Grandparent如下方式连接:

class Grandparent {
  set myField(value) {
    console.log('Grandparent setter');
  }
}

class Parent extends Grandparent {
  set myField(value) {
    console.log('Parent setter');
  }
}

class Child extends Parent {
  set myField(value) {
    //I know how to call Parent's setter of myField:
    //super.myField = value;
    //But how to call Grandparent's setter of myField here?
  }
}

我怎样才能在类的二传手中调用'Grandparent二传手?myFieldChild

我对设置器特别感兴趣,而不是方法。此外,最好不要更改ParentGrandparent

我看不出这是如何使用的,super因为它只引用Parent类,以及使用类似的东西,Grandparent.prototype.<what?>.call(this, ...)因为我不知道在原型中究竟要调用什么。

有人对这个案子有什么建议吗?

提前致谢!

标签: javascriptecmascript-6es6-class

解决方案


使用类似的东西Grandparent.prototype.<what?>.call(this, ...)

您在正确的轨道上,您可以使用以下方法访问 setter 方法Object.getOwnPropertyDescriptor

Object.getOwnPropertyDescriptor(Grandparent.prototype, "myField").set.call(this, value);

不过有一个更简单的方法:使用带有自定义接收器的Reflect.set助手:

Reflect.set(Grandparent.prototype, "myField", value, this);

这还有一个优点,即在Grandparent未定义 setter 时它仍然有效。


也就是说,我同意@Dinu 的观点,即当您需要这样做时,您的类层次结构(或您的一般设计,也许您甚至不应该使用类或继承)可能存在问题。


推荐阅读