我试图得到如下结果
let hobbes = new Employee("Hobbes", 1000000, "Founder", null);
console.log(hobbes.bonus(0.05)); // 50000
let calvin = new Manager("Calvin", 130000, "Director", "Hobbes");
console.log(calvin.bonus(0.05)); // 6500
let susie = new Manager("Susie", 100000, "TA Manager", "Calvin");
console.log(susie.bonus(0.05)); // 14000
let lily = new Employee("Lily", 90000, "TA", "Susie");
console.log(lily.bonus(0.05)); // 4500
let clifford = new Employee("Clifford", 90000, "TA", "Susie");
console.log(clifford.bonus(0.05)); // 4500
但是我对从经理的女员工那里获得薪水感到困惑。从论文类。指示是。 您可以将计算一个经理的所有员工的总工资的逻辑提取到一个 totalSubsalary() 方法中。 为此,您可以遍历经理的每个员工,检查该员工是否是经理的实例,并计算总Subsalary。
class Employee {
constructor(name, salary, title, bosss) {
this.name = name;
this.title = title;
this.salary = salary;
this.bosss = bosss;
}
bonus(multiplier) {
return this.salary * multiplier;
}
}
class Manager extends Employee {
constructor(name, salary, title, employees) {
super(name, salary, title);
this.employees = employees;
}
bonus(multiplier) {
return this.salary * multiplier;
}
totalSubSalary() {
for (let key in this.employees) {
const element = this.employees;
console.log(this.name instanceof Manager);
}
}
}
答案 0 :(得分:0)
您可以先创建所有员工。然后创建经理并将员工数组传递给经理构造函数。
class Employee {
constructor(name, salary, title) {
this.name = name;
this.title = title;
this.salary = salary;
this.bosss = null; // The manager will assign this
}
bonus(multiplier) {
return this.salary * multiplier;
}
}
class Manager extends Employee {
constructor(name, salary, title, employees) {
super(name, salary, title);
// employees should be an array of Employee objects
this.employees = employees;
// Assign each employees manager to me
this.employees.forEach((e) => {
e.bosss = this;
});
}
// No need to override bonus() function
totalSubSalary() {
return this.employees.reduce((a, b) => {return a + b.salary;}, 0);
}
}
// Create the employees
let hobbes = new Employee("Hobbes", 1000000, "Founder");
console.log(hobbes.bonus(0.05)); // 50000
let lily = new Employee("Lily", 90000, "TA");
console.log(lily.bonus(0.05)); // 4500
let clifford = new Employee("Clifford", 90000, "TA");
console.log(clifford.bonus(0.05)); // 4500
// Create the managers
let calvin = new Manager("Calvin", 130000, "Director", [hobbes]);
console.log(calvin.bonus(0.05)); // 6500
let susie = new Manager("Susie", 100000, "TA Manager", [lily, clifford]);
console.log(susie.bonus(0.05)); // 5000
console.log(susie.totalSubSalary());