I have the following class structure.
const {EmployeeRequestExecutor} = require('./EmployeeRequestExecutor');
class EmployeeService {
fulfill(request){
EmployeeRequestExecutor.delegateEmployeeRequest(request);
}
}
module.exports = {EmployeeService};
const {HelpfulEmployee} = require('./HelpfulEmployee');
class EmployeeRequestExecutor {
static delegateEmployeeRequest(request){
let employee = new HelpfulEmployee();
employee.work(request);
}
static executeEmployeeRequest(request){
console.log('Executed', request);
}
}
module.exports = {EmployeeRequestExecutor};
const {EmployeeRequestExecutor} = require('./EmployeeRequestExecutor');
class HelpfulEmployee {
work(request){
EmployeeRequestExecutor.executeEmployeeRequest(request);
}
}
module.exports = {HelpfulEmployee};
If we then do
let employeeService = new EmployeeService();
employeeService.fulfill(request);
we get TypeError: Cannot read property 'executeEmployeeRequest' of undefined in HelpfulEmployee.js:5:33
Why is it so that with such call structure EmployeeRequestExecutor
inside HelpfulEmployee.js
is undefined?
There is a circular dependency between HelpfulEmployee and EmployeeRequestExecutor (they both require each other). Circular dependencies result most of the time from class design issues. To fix them, you should reconsider the flow of information between your objects.
This is an option, but there are many more:
const {HelpfulEmployee} = require('./HelpfulEmployee');
class EmployeeRequestExecutor {
static delegateEmployeeRequest(request){
let employee = new HelpfulEmployee();
let requestExecutor = new EmployeeRequestExecutor();
employee.work(request, requestExecutor);
}
executeEmployeeRequest(request){
console.log('Executed', request);
}
}
module.exports = {EmployeeRequestExecutor};
class HelpfulEmployee {
work(request, requestExecutor){
requestExecutor.executeEmployeeRequest(request);
}
}
module.exports = {HelpfulEmployee};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments