如何在子类中仅覆盖一个 getter?

huangapple go评论71阅读模式
英文:

How can I override just a getter in a subclass?

问题

如果我有一个具有getter和setter的基类,并且在子类中覆盖getter(但不覆盖setter),我会收到Cannot set property x of #<MyClass> which has only a getter的错误消息。我真的需要在我的子类中有这样一个多余的方法吗:

set x(val: any) {
  super.x = val;
}
英文:

If I have a base class that has a getter and setter, and I override the getter in a subclass (but not the setter), I am getting Cannot set property x of #<MyClass> which has only a getter ... Do I really have to have such a superfluous method in my subclass like:

set x(val: any) {
  super.x = val;
}

??

答案1

得分: 2

这是原型继承在JavaScript中的工作原理。

Getter和setter不是分开的函数。它们在单个PropertyDescriptor中定义,因此它们是相关联的。虽然每个都是可选的,但如果定义了一个,另一个也会被定义为undefined

当你覆盖x属性时,你正在覆盖属性描述符。当JavaScript尝试查找属性时,它会在MyClass中找到PropertyDescriptor,而该PropertyDescriptor没有getter。

因此,你已经使用的解决方案(super.x = val)是处理覆盖setter但仍然使用super的getter的适当方式。

英文:

This is how prototypical inheritance works in JavaScript.

A getter and a setter are not separate functions. They are defined in a single PropertyDescriptor and are thus linked. While each is optional, if one is defined then so is the other (as undefined).

When you override the x property, you are overriding the property descriptor. When JavaScript attempts to look up the property, it finds the PropertyDescriptor in MyClass and that PropertyDescriptor has no getter.

So the solution you have already used (super.x = val) is the appropriate way to handle overriding a setter while still using the super's getter.

答案2

得分: 0

这是一些非常奇怪的事情,根据ES6,我经历了这样一个设计问题,即无论是get还是set都必须在子类中定义。作为一种解决方法,我最终定义了方法而不是访问器。

class A {
    protected _val: number;
    getval(): number {
        return this._val;
    }
}

class B extends A {
    setval(value: number) {
        this._val = value;
    }
}

有一个较长的讨论主题在这里

英文:

This is something really weird, as per ES6 i experienced that lets say design issue, both get and set must be defined on child class. As a work around i ended up defining methods instead of accessors.

class A
{
    protected _val:number;
    getval():number
    {
        return this._val;
    }

}

class B extends A
{

    setval(value:number)
    {
        this._val = value;
    }

}

Theres a large thread here

huangapple
  • 本文由 发表于 2023年6月1日 03:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定