简体   繁体   English

在Node中递归地需要模块

[英]Recursively requiring modules in Node

So, let's say I have two classes, each of which requires the other: 因此,假设我有两个类,每个类都需要另一个:

Department.js: Department.js:

const Person = require("./Person");
class Department{
  constructor(id){
    this.personel = getPersonel(id).map(person => new Person(person));
  }
}

Person.js 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;

Now, this doesn't work, and I can kinda understand why. 现在,这不起作用,我可以理解为什么。 It says "Person" is not a constructor at Department.js. 它说“ Person”不是Department.js的构造函数。 However, if I put both classes in the same file, it works just fine. 但是,如果我将两个类都放在同一个文件中,则效果很好。

So; 所以; my question is, how do I work around this? 我的问题是,我该如何解决? I'd really rather not keep both of these classes in the same file -- is there a better way? 我真的不想将这两个类都放在同一个文件中-有更好的方法吗?

I'm running the latest version of Node. 我正在运行最新版本的Node。

You can separate initializing objects from fetching data: 您可以将初始化对象与获取数据分开:

// 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);
}

These can even go back on the types ( findDepartment.jsDepartment.js , Department.findDepartment = function (id) { … ) if you really want. 如果您确实需要,它们甚至可以返回类型( findDepartment.jsDepartment.jsDepartment.findDepartment = function (id) { … ))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM