ES6类继承问题:Employee实例调用doWork未返回预期值
问题分析与解决
嘿,我来帮你拆解这个问题!你遇到的核心问题是Employee类并没有重写Person类的doWork()方法,所以你的connor实例调用doWork时,实际执行的是父类Person里的方法,自然返回的是'Paid Employee',而不是你期望的'Employee Paid'。
先理清楚继承链的逻辑
你的类继承关系是:Intern → Employee → Person
- Intern类自己重写了doWork(),所以beth实例调用时用的是自己的方法,返回'Intern Free',完全符合预期。
- Employee类没有定义自己的doWork(),所以它会直接继承Person类的doWork()方法,因此connor调用doWork()时,会沿着原型链找到Person中的方法,返回'Paid Employee'。
解决方法:给Employee类添加重写的doWork()方法
只需要在Employee类里补充doWork()方法,返回你期望的'Employee Paid'即可。修改后的完整代码如下:
class Person { constructor(name) { this.name = name; } get name() { return this._name; } set name(newValue) { if(newValue) { this._name = newValue; } } doWork() { return 'Paid Employee'; } } class Employee extends Person { constructor(title, name) { super(name); this._title = title; } get title() { return this._title; } // 这里添加重写的doWork方法 doWork() { return 'Employee Paid'; } } class Intern extends Employee { doWork() { return 'Intern Free' } } let makeEveryoneWork = function(...people) { var results = []; for(var i = 0; i < people.length; i++) { results.push(people[i].doWork()); } return results } let connor = new Employee("Doctor", "Connor"); let beth = new Intern("Student", "Beth"); console.log(connor.doWork()); // 现在会返回'Employee Paid' console.log(beth.doWork()); // 返回'Intern Free' console.log(makeEveryoneWork(connor, beth)); // 输出 ["Employee Paid", "Intern Free"]
验证修改后的结果
当你添加了Employee类的doWork()方法后,connor实例调用该方法时,会优先使用自身类定义的方法,而不会再去调用Person类的方法,这样就完全符合你的预期了。
内容的提问来源于stack exchange,提问作者user3574939
相关产品推荐
相关产品推荐

