RequireJS:如何定义包含单个“类”的模块?

2024-01-03

我有许多 JavaScript“类”,每个类都在自己的 JavaScript 文件中实现。对于开发,这些文件是单独加载的,对于生产,它们是串联的,但在这两种情况下,我都必须手动定义加载顺序,确保如果 B 使用 A,则 B 在 A 之后。我打算使用要求JS http://requirejs.org/作为一个实施CommonJS 模块/异步定义 http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition自动为我解决这个问题。

有没有比定义每个导出一个类的模块更好的方法?如果没有,如何命名模块导出的内容?模块“employee”导出类“Employee”,如下例所示,感觉不到DRY http://en.wikipedia.org/wiki/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");
});

The AMD提案 http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition允许您只返回导出对象的值。但请注意,这是 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");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RequireJS:如何定义包含单个“类”的模块? 的相关文章

随机推荐