javascript - 如何在Javascript中调用祖父母类的setter
问题描述
想象一下,我有 3 个类Child
,Parent
并按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
二传手?myField
Child
我对设置器特别感兴趣,而不是方法。此外,最好不要更改Parent
类Grandparent
。
我看不出这是如何使用的,super
因为它只引用Parent
类,以及使用类似的东西,Grandparent.prototype.<what?>.call(this, ...)
因为我不知道在原型中究竟要调用什么。
有人对这个案子有什么建议吗?
提前致谢!
解决方案
使用类似的东西
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 的观点,即当您需要这样做时,您的类层次结构(或您的一般设计,也许您甚至不应该使用类或继承)可能存在问题。
推荐阅读
- python - Unexpected keyword argument 'ragged' in Keras
- java - 如何在 Android 应用程序的两个模块之间传递变量(本地语言)?
- python - 尝试使用 opencv 的 fillPolly 将多边形添加到图像上时出错
- google-cloud-platform - Cloud Pub/Sub 上未确认的消息
- c++ - VB.NET DLL中的C++ DLL函数复制
- reactjs - 将主组件状态传递给另一个组件错误
- outlook - 在 Outlook 中按“发送”按钮后如何添加通知窗口?
- spring-boot - 如何在 groovy 中使用 Spring 表达式语言(SpEL)?(每个春季调度程序crontab)
- angular - 需要在页面之间维护表单数据,而无需在 angular-ngrx 页面中向服务器/api 发送数据
- c# - 如何在父类的自定义用户控件中设置自定义验证错误模板的属性