因此,假设我有两个类,每个类都需要另一个:
Department.js:
const Person = require("./Person");
class Department{
constructor(id){
this.personel = getPersonel(id).map(person => new Person(person));
}
}
Person.js
const Department = require("./Department");
class Person {
constructor(id){
this.department = new Department(getDeptOfPerson(id));
}
}
const person = new Person(1);
const coworkers = person.department.personel;
现在,这不起作用,我可以理解为什么。它说“ Person”不是Department.js的构造函数。但是,如果我将两个类都放在同一个文件中,则效果很好。
所以;我的问题是,我该如何解决?我真的不想将这两个类都放在同一个文件中-有更好的方法吗?
我正在运行最新版本的Node。
最佳答案
您可以将初始化对象与获取数据分开:
// types/Department.js
class Department {
constructor(id, personnel) {
this.id = id;
this.personnel = personnel;
}
}
// types/Person.js
class Person {
constructor(id, department) {
this.id = id;
this.department = department;
}
}
// findDepartment.js
const Department = require('./types/Department');
const Person = require('./types/Person');
function findDepartment(id) {
const personnel = getPersonnel(id).map(person => new Person(person));
return new Department(id, personnel);
}
// findPerson.js
const Department = require('./types/Department');
const Person = require('./types/Person');
function findPerson(id) {
const department = getDeptOfPerson(id);
return new Person(id, department);
}
如果您确实需要,甚至可以返回这些类型(
findDepartment.js
→Department.js
,Department.findDepartment = function (id) { …
)。关于javascript - 在Node中递归地需要模块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47729564/