我有许多 JavaScript“类”,每个类都在其自己的 JavaScript 文件中实现。对于开发,这些文件是单独加载的,对于生产,它们是串联的,但在这两种情况下,我都必须手动定义加载顺序,确保如果 B 使用 A,则 B 在 A 之后。我打算使用 RequireJS作为 CommonJS Modules/AsynchronousDefinition 的实现自动为我解决这个问题。
有没有比定义每个导出一个类的模块更好的方法呢?如果不是,你如何命名模块导出的内容?导出类“Employee”的模块“employee”,如下例所示,感觉不到 DRY对我来说足够了。
define("employee", ["exports"], function(exports) {
exports.Employee = function(first, last) {
this.first = first;
this.last = last;
};
});
define("main", ["employee"], function (employee) {
var john = new employee.Employee("John", "Smith");
});
最佳答案
AMD proposal允许您只为导出的对象返回一个值。但请注意,这是 AMD 提议的一个特性,它只是一个 API 提议,并且会使将模块转换回常规 CommonJS 模块变得更加困难。我认为这没问题,但需要了解有用的信息。
因此您可以执行以下操作:
我更喜欢导出构造函数的模块以大写名称开头,因此该模块的非优化版本也会在 Employee.js 中
define("Employee", function () {
//You can name this function here,
//which can help in debuggers but
//has no impact on the module name.
return function Employee(first, last) {
this.first = first;
this.last = last;
};
});
现在在另一个模块中,您可以像这样使用 Employee 模块:
define("main", ["Employee"], function (Employee) {
var john = new Employee("John", "Smith");
});
关于javascript - RequireJS:如何定义包含单个 "class"的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4869530/