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 类中,这将覆盖 set
和 get
的定义:
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/