在我的系统中,我在浏览器中加载了许多“类”,每个类在开发过程中都是一个单独的文件,并连接在一起用于生产。当它们被加载时,它们在全局对象上初始化一个属性,这里G
,如本例所示:
var G = {};
G.Employee = function(name) {
this.name = name;
this.company = new G.Company(name + "'s own company");
};
G.Company = function(name) {
this.name = name;
this.employees = [];
};
G.Company.prototype.addEmployee = function(name) {
var employee = new G.Employee(name);
this.employees.push(employee);
employee.company = this;
};
var john = new G.Employee("John");
var bigCorp = new G.Company("Big Corp");
bigCorp.addEmployee("Mary");
根据James Burke 的建议,我没有使用我自己的全局对象,而是考虑让每个类都有自己的AMD module:
define("Employee", ["Company"], function(Company) {
return function (name) {
this.name = name;
this.company = new Company(name + "'s own company");
};
});
define("Company", ["Employee"], function(Employee) {
function Company(name) {
this.name = name;
this.employees = [];
};
Company.prototype.addEmployee = function(name) {
var employee = new Employee(name);
this.employees.push(employee);
employee.company = this;
};
return Company;
});
define("main", ["Employee", "Company"], function (Employee, Company) {
var john = new Employee("John");
var bigCorp = new Company("Big Corp");
bigCorp.addEmployee("Mary");
});
问题是之前,员工和公司之间没有声明时依赖:你可以按照你想要的任何顺序放置声明,但是现在,使用 RequireJS,这引入了一个依赖,它在这里(故意)循环,所以上面的代码失败。当然,在 中addEmployee()
,添加第一行var Employee = require("Employee");
会使其工作,但我认为此解决方案不如不使用 RequireJS/AMD,因为它要求我(开发人员)注意这个新创建的循环依赖并对此做一些事情。
有没有更好的方法用 RequireJS/AMD 解决这个问题,或者我是否将 RequireJS/AMD 用于它不是设计的东西?