classDerivedextendsBase {
constructor(publicname:string, age, salary) {
super(age, salary);
}
get Age() {
// ✅ 保护的属性可以从继承类中获取到returnthis.age;
}
get Salary() {
// ? Property '_salary' is private and only accessible within class 'Base'.ts(2341)returnthis._salary;
}
}
然后分别实例化这两个类:
const base =newBase(18, 999);
const derived =newDerived("derived", 20, 1000);
然后通过他们的实例尝试访问这些属性。
// ?Property '_salary' is private and only accessible within class 'Base'.ts(2341)console.log(base._salary);
// ?Property 'age' is protected and only accessible within class 'Base' and its subclasses.ts(2445)console.log(base.age);