How to handle circular dependencies with RequireJS/AMD?

This is indeed a restriction in the AMD format. You could use exports, and that problem goes away. I find exports to be ugly, but it is how regular CommonJS modules solve the problem:

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

Otherwise, the require(“Employee”) you mention in your message would work too.

In general with modules you need to be more aware of circular dependencies, AMD or not. Even in plain JavaScript, you have to be sure to use an object like the G object in your example.

Leave a Comment