RequireJS:如何定义包含单个“类”的模块? [英] RequireJS: How to define modules that contain a single "class"?
问题描述
我有许多JavaScript类,每个类都在自己的JavaScript文件中实现。对于开发,这些文件是单独加载的,并且为了生产它们是连接的,但在这两种情况下我都必须手动定义加载顺序,确保B在A之后,如果B使用A.我打算使用 RequireJS 作为 CommonJS Modules / AsynchronousDefinition 自动为我解决这个问题。
I have a number of JavaScript "classes" each implemented in its own JavaScript file. For development those files are loaded individually, and for production they are concatenated, but in both cases I have to manually define a loading order, making sure that B comes after A if B uses A. I am planning to use RequireJS as an implementation of CommonJS Modules/AsynchronousDefinition to solve this problem for me automatically.
有没有更好的方法来定义每个导出一个类的模块?如果没有,您如何命名模块导出的内容?导出类员工的模块员工,如下例所示,感觉不到 DRY 足够我。
Is there a better way to do this than to define modules that each export one class? If not, how to you name what the module exports? A module "employee" exporting a class "Employee", as in the example below, doesn't feel DRY enough to me.
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提案允许您只返回导出对象的值。但请注意,这是AMD提案的一个特性,它只是一个API提案,并且会使将模块转换回常规CommonJS模块变得更加困难。我认为这很好,但有用的信息要知道。
The AMD proposal allows you to just return a value for the exported object. But note that is a feature of the AMD proposal, it is just an API proposal, and will make it harder to translate the module back to a regular CommonJS module. I think that is OK, but useful info to know.
所以你可以做以下事情:
So you can do the following:
I更喜欢导出构造函数的模块以大写名称开头,因此该模块的非优化版本也将在Employee.js中
I prefer modules that export a constructor function to start with an upper-case name, so the non-optimized version of this module would also be in 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模块,如下所示:
Now in another module, you can use the Employee module like so:
define("main", ["Employee"], function (Employee) {
var john = new Employee("John", "Smith");
});
这篇关于RequireJS:如何定义包含单个“类”的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!