RequireJS,循环依赖和出口“魔法”方法

时间:2015-01-28 13:23:23

标签: javascript requirejs circular-dependency

我一直试图按照the special 'exports' magic moduleJames Burke's answer的建议,使用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包含为define回调函数的参数,它只是在两种情况下初始化为空,并且不包含它所分配的构造函数。

我做错了什么?

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

1 个答案:

答案 0 :(得分:3)

编辑:我无法找到有关魔术导出方法的更多信息。但是,我可以用虚拟的容器模拟它的预期行为。模块。在这个小提琴中看到它: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"]);