TypeScript super实现无法取值:Employee类不存在name属性报错问题
错误原因
- 你在
Person类中定义的#name是JS原生私有字段,带#前缀的私有字段是严格类私有属性,仅允许在声明该字段的类内部直接访问,子类、类外部均无法直接读取,所以你在子类Employee中直接访问this.name会报属性不存在的错误:你从来没有声明过公开的name属性,父类仅对外暴露了getName()方法读取私有姓名。 - 你的代码还存在一处隐藏错误:
giveRaise方法中await this.#storySalary漏了方法调用括号,正确写法是await this.#storySalary(),否则你await的是函数本身而非执行后的Promise对象。
修复方案
将Employee类中所有this.name替换为调用父类公开方法this.getName()即可,修正后的完整代码如下:
class Person { #name:string; getName(){ return this.#name; } constructor(name:string){ this.#name = name; } } class Employee extends Person { #salary:number; constructor(name:string, salary:number = 0){ super(name); this.#salary = salary; } async giveRaise(raise:number):Promise<void> { this.#salary += raise; await this.#storySalary(); } pay():void { console.log(`¤ ${this.#salary} is paid to ${this.getName()}.`); } async #storySalary():Promise<void> { console.log(`Salary ¤ ${this.#salary} is stored for ${this.getName()}`); } } const NewEmployee = new Employee('Sha', 300); console.log(NewEmployee.getName(), NewEmployee.pay())
内容的提问来源于stack exchange,提问作者3gwebtrain
相关产品推荐
相关产品推荐

