I have two files, employee.js
const Manager = require('./manager.js');
let manager = new Manager();
class Employee {
constructor(name, title, salary, boss=null)
{
this.name = name;
this.title = title;
this.salary = salary;
this.boss = boss;
manager.addEmployee(this.Employee);
}
}
module.exports = Employee;
And manager.js
const Employee = require('./employee.js');
class Manager extends Employee {
constructor(name, salary, title, boss=null) {
// this.name = name;
// this.title = title;
// this.salary = salary;
// this.boss = boss;
super(name, salary, title, boss);
this.managedEmployees = [];
}
addEmployee(Employee) {
this.managedEmployees.push(Employee);
}
}
let annie = new Manager('annie', 100000, 'Director');
let alvy = new Employee('alvy', 75000, 'Analyst', annie);
console.log(annie);
module.exports = Manager;
I am desperately trying to find what syntax would allow me to take the addEmployee(Employee) method and call it in the constructor of the Employee class. I want Manager to be the child of Employee and have an array of all the employees under the manager. The method is pushing into the array but I cannot figure out what I should be doing for console.log(annie); to end up with this input
<ref *1> Manager {
name: 'Annie',
salary: 100000,
title: 'Director',
manager: null,
employees: [
Employee {
name: 'Alvy',
salary: 75000,
title: 'Analyst',
manager: [Circular *1]
}
]
}
Setup your Employee class like this:
class Employee {
constructor(name, title, salary, boss=null)
{
this.name = name;
this.title = title;
this.salary = salary;
this.boss = boss;
if (boss) {
boss.addEmployee(this);
}
}
}
You're passing in an instanceof Manager, so if it's not null you can call a method on that. Notice that you want to just pass this as the input to addEmployee, as this.Employee is trying to access a property or method in that class which doesn't exist.
Console output will look something like this:
Manager {
name: "annie",
title: 100000,
salary: "Director",
boss: null,
managedEmployees: [
Employee {
name: "alvy",
title: 75000,
salary: "Analyst",
boss:Manager {...}
}
]
}
You will also notice that you have the order of parameters swapped for title/salary on your Employee constructor.