注意这个版本带有公共(public)方法message()
编译和greet()
按预期工作,
class Foo {
public greet() {
console.log(`Hello, ${this.getMessage()}`);
}
getMessage() : string {
return "I am Foo"
}
}
class Goo extends Foo {
getMessage() : string {
return "I am Goo";
}
}
但与 getMessage()
标记为私有(private),Goo 类不再编译:class Foo {
public greet() {
console.log(`Hello, ${this.getMessage()}`);
}
private getMessage() : string {
return "I am Foo"
}
}
class Goo extends Foo {
private getMessage() : string {
return "I am Goo";
}
}
正如许多关于该主题的书籍所推荐的那样,我经常使用私有(private)方法通过抽象出低级代码块以提高可读性来分解更大的方法,并且我将它们设为私有(private),因为它们不打算由类的消费者调用,而是为了当需要为我的基类的某些子类修改这些较低级别的方法之一时, typescript 对我不利。实际上,除了必须在扩展类中实现公共(public)方法之外,还有其他方法可以做到这一点,或者通过将支持方法包含在基类和子类的公共(public)接口(interface)中来暴露支持方法的“脏衣服”?
另外,我想知道 typescript 作者的动机是什么,因为这个看似任意的规则是公共(public)方法可以被覆盖但私有(private)方法不能被覆盖?
最佳答案
正如 bryan60 所说,使用 protected
修饰符:
class Foo {
public greet() {
console.log(`Hello, ${this.getMessage()}`);
}
protected getMessage(): string {
return "I am Foo";
}
}
class Goo extends Foo {
protected getMessage(): string {
return "I am Goo";
}
}
const goo = new Goo();
goo.greet(); // Hello, I am Goo
来自 the handbook :The
protected
modifier acts much like theprivate
modifier with the exception that members declaredprotected
can also be accessed within deriving classes.
例如:
// Property 'getMessage' is protected and only accessible within class 'Goo'
// and its subclasses.
goo.getMessage();
class Hoo extends Goo {
public getMessage(): string {
return "I am Hoo";
}
public tryToGetGoosMessage(goo: Goo): string {
// Property 'getMessage' is protected and only accessible through an
// instance of class 'Hoo'.
return goo.getMessage();
}
public doOtherHoosHoo(hoo: Hoo) {
// ok, this is inside Hoo
hoo.hoo();
}
protected hoo() {}
}
const hoo = new Hoo();
// ok, getMessage is public in Hoo
hoo.getMessage();
// Class 'Joo' incorrectly extends base class 'Hoo'.
// Property 'getMessage' is protected in type 'Joo' but public in type 'Hoo'.
class Joo extends Hoo {
protected getMessage(): string {
return "I am Joo";
}
}
Playground link
关于typescript - 重写 typescript 中的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64083601/