在我的系统中,我在浏览器中加载了许多“类”,每个类在开发过程中都是一个单独的文件,并串联在一起进行生产。加载它们时,它们在全局对象(这里)上初始化一个属性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模块:
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");
});
问题在于,以前,Employee和Company之间没有声明时间依赖关系:您可以按所需的顺序放置声明,但是现在,使用RequireJS引入了依赖关系,在这里(有意地)是循环的,因此以上代码失败。当然,在addEmployee()
补充一线var Employee = require("Employee");
将使它的工作,但我看到这个解决方案,不如不使用RequireJS / AMD,因为它需要我,开发商,要知道这个新创建循环依赖,并做一些事情。
是否有更好的方法来解决RequireJS / AMD的问题,还是我将RequireJS / AMD用于并非为它设计的东西?
function(exports, Company)
和function(exports, Employee)
。无论如何,感谢RequireJS,这太棒了。