javascript - ES6 类继承不继承
问题描述
我正在学习 ES6 视频教程并重新创建用例以更好地理解语法。
我是关于类继承的主题。我创建了一个由 Employee 扩展的超类 Person,我还有一个扩展 Employee 的实习生类。我doWork()
在 Person 类中有一个名为“”的函数,它返回“paid”,在 Intern 类中,我试图通过让它返回“free”来覆盖“doWork”。
我指定康纳为新员工,贝丝为新实习生。问题是在我调用 doWork() 之后,我只在来自 beth.doWork() 的 console.log 中看到“Intern Free”。connor.doWork() 不应该返回“Employee Paid”,因为 Employee 正在扩展 Person 类?
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;
}
}
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");
connor.doWork(); //expecting to be 'Employee Paid'
beth.doWork(); // exprecting to be 'Intern Free'
解决方案
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;
}
}
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()) //expecting to be 'Employee Paid'
console.log(beth.doWork()) // exprecting to be 'Intern Free'
对我来说没问题。运行代码段。我只是复制粘贴了您的代码,并稍作更改。我将最后两行包裹在 console.log 调用中。
推荐阅读
- python - 通过 form.py 上传图片
- javascript - 用if语句jquery改变颜色
- git - 使用 Git 工具在一个 Git 存储库下添加多个项目 - 子模块
- c++ - Qt信号多重定义
- python - Python:我可以在 map 函数中使用 dict update 吗?
- docker - 在 Docker Hub 上哪里可以找到官方镜像的 Dockerfile?
- javascript - 如何使用 Vue 为 VSCode 创建扩展
- angular - 我如何拥有两个具有不同基本 html 的页面?
- xamarin - 4.7 的新功能 - 寻找一种在 C# 中指定 RowDefinitions="1*, Auto, 25, 14, 20" 的方法
- python-3.x - Flask:send_file() 完成后从服务器删除文件