gpt4 book ai didi

javascript - B 扩展 A : set in B will overwrite get

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:24 26 4
gpt4 key购买 nike

typescript :view on playground

class A {
protected _name: string = ""

set name(name: string) {
this._name = name
}
get name() {
return this._name
}
}

class B extends A {
protected _name: string = ""

set name(name: string) {
this._name = name + "B"
}
}

在编译的 B 类中,这将覆盖 setget 的定义:

Object.defineProperty(B.prototype, "name", {
set: function (name) {
this._name = name + "B";
},
enumerable: true,
configurable: true
});

结果是,get name 在类 B 上不再起作用:

let b = new B()
b.name = "test"
console.log(b.name) // undefined

有没有办法从A类继承getter?

最佳答案

以下代码在 TypeScript 编译器中运行,没有任何错误:

class A {
protected _name: string = ""

set name(name: string) {
this._name = name
}
get name() {
return this._name
}
}

class B extends A {
// Removed _name declaration here

set name(name: string) {
super["name"] = name + "B" // <=== Using super here
}
get name() {
return super["name"] // <=== And here
}
}

var b = new B();
b.name = "foo";
console.log(b.name); // "fooB"

与@Crowder 的代码唯一不同的是,我使用的不是 super.name super["name"]。如果您使用 super.name,编译器将发出此错误:Only public and protected methods of the base class are accessible via the 'super' keyword。请注意:TypeScript 在发现错误时仍会编译,因此使用 super.name 也可以,尽管有错误。

关于javascript - B 扩展 A : set in B will overwrite get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com