在Node中递归地要求模块

时间:2017-12-09 14:26:35

标签: javascript node.js

所以,让我们说我有两个课程,每个课程都需要另一个课程:

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;

现在,这不起作用,我可以理解为什么。它说"人"不是Department.js的构造函数。但是,如果我将两个类放在同一个文件中,它就可以正常工作。

因此;我的问题是,我该如何解决这个问题?我真的不愿意将这两个类保存在同一个文件中 - 有更好的方法吗?

我正在运行最新版本的Node。

1 个答案:

答案 0 :(得分:1)

您可以将初始化对象与提取数据分开:

$('#aa-search-input').autocomplete(
  {
    hint: true,
    minLength: 2,
  }, [
    {
      source: $.fn.autocomplete.sources.hits(resources, { hitsPerPage: 3 }),
      displayKey: 'name',
      templates: {
        header: '<div class="aa-suggestions-category">Resources</div>',
        suggestion: function(suggestion) {
          return '<span>' +
          suggestion._highlightResult.name.value + '</span><span>'
          + suggestion._highlightResult.write_up.value + '</span>';
        },
      empty: '<div class="aa-empty">No matching resources <i class="frown icon"></i></div>',
    }
  },
  {
    source: $.fn.autocomplete.sources.hits(users, { hitsPerPage: 3 }),
      displayKey: 'name',
      templates: {
        header: '<div class="aa-suggestions-category">Users</div>',
        suggestion: function(suggestion) {
          return '<span>' +
            suggestion._highlightResult.username.value + '</span>';
          },
      empty: '<div class="aa-empty">No matching users <i class="frown icon"></i></div>',
      }
    }
  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
    location.href = '/resources/view/show-' + suggestion.id;
});

如果您真的想要,这些甚至可以返回类型(// 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.jsDepartment.js)。