RequireJS、循环依赖和导出 "Magic" 方法

RequireJS, Circular Dependencies and Exports "Magic" Method

我一直在尝试使用 the special 'exports' magic module as recommended by James Burke's answer to this question.

设置 RequireJS 来处理循环依赖

按照@jrburke 在该问题中给出的示例:

define("Employee", ["exports", "Company"], function(Company) {
    function Employee(name) {
        this.name = name;
        this.company = new Company.Company(name + "'s own company");
    };
    exports.Employee = Employee;
});
define("Company", ["exports", "Employee"], function(Employee) {
    function Company(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Employee.Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    exports.Company = Company;
});

jsfiddle

问题是使用他自己的例子,exports模块是未定义的,因此exports.Employeeexports.Company没有设置。如果我尝试将 exports 作为定义回调函数的参数包含在内,它会在两种情况下简单地初始化为空,并且不携带分配给它的构造函数。

我做错了什么?

编辑:通过反复试验,我得到了上面的代码:http://jsfiddle.net/jpk45vow/4/。任何人都可以解释 为什么 它有效,因为它对我来说毫无意义。

编辑: 我找不到有关魔法导出方法的更多信息。但是,我可以使用虚拟 "Container" 模块来模仿其预期行为。见此fiddle:http://jsfiddle.net/amenadiel/a7thxz98/

console.log("start");

define("Container",function() {
    var Container={};
    return Container;
});


define("Employee", ["Container"], function(Container) {
    var Employee= function(name) {
        this.name = name;
        this.company = new Container.Company(name + "'s own company");
    };
    Container.Employee = Employee;
});

define("Company", ["Container"], function(Container) {
    var Company=function(name) {
        this.name = name;
        this.employees = [];
    };
    Company.prototype.addEmployee = function(name) {
        var employee = new Container.Employee(name);
        this.employees.push(employee);
        employee.company = this;
    };
    Container.Company = Company;
});

define("main", ["Container","Employee","Company" ], function ( Container) {
    var john = new Container.Employee("John");
    var bigCorp = new Container.Company("Big Corp");
    bigCorp.addEmployee("Mary");
    console.log(bigCorp);
});

require(["main"]);