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

IT技术 javascript commonjs requirejs
2021-03-03 23:47:42

我有许多 JavaScript“类”,每个类都在自己的 JavaScript 文件中实现。对于开发,这些文件是单独加载的,对于生产它们是串联的,但在这两种情况下,我都必须手动定义加载顺序,确保如果 B 使用 A,则 B 在 A 之后。我计划使用RequireJS作为CommonJS Modules/AsynchronousDefinition自动为我解决这个问题。

有没有比定义每个导出一个类的module更好的方法呢?如果没有,您如何命名module导出的内容?如下例所示,导出类“Employee”的module“employee”对我来说感觉不够干燥

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");
});
2个回答

AMD的建议可以让你只返回一个值导出的对象。但请注意,这是 AMD 提案的一个特性,它只是一个 API 提案,并且会使将module转换回常规 CommonJS module变得更加困难。我认为没关系,但要了解有用的信息。

因此,您可以执行以下操作:

我更喜欢导出构造函数以大写名称开头的module,因此该module的非优化版本也将在 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;
    };
});

现在在另一个module中,您可以像这样使用 Employee module:

define("main", ["Employee"], function (Employee) {
    var john = new Employee("John", "Smith");
});
哇,直接来自@jrburke 的回答,先生。RequireJS 自己!+1!
2021-05-06 23:47:42

作为 jrburke 答案的补充,请注意您不必直接返回构造函数。对于大多数有用的类,您还需要通过原型添加方法,您可以这样做:

define('Employee', function() {
    // Start with the constructor
    function Employee(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // Now add methods
    Employee.prototype.fullName = function() {
        return this.firstName + ' ' + this.lastName;
    };

    // etc.

    // And now return the constructor function
    return Employee;
});

事实上,这正是requirejs.org 上这个示例中显示的模式

@NathanPrather 这是一个很好的参考——这些评论帮助我从 Java 背景中翻译出来
2021-04-18 23:47:42
嗨,马克,你的帖子正是我要找的。除了一件事。是否可以为 Employee 对象定义一些不属于构造函数的字段?例如,具有位置属性和方法 positionToUpper,但不知何故在构造函数中定义该属性,而不是在员工 = new Employee ('john', 'smith'); 中。员工职位 = '经理'; 警报(员工。positionToUpper());
2021-05-07 23:47:42
亚历克斯,这个例子对我很有帮助,它有很好的文档记录,可能可以提供你正在寻找的例子: gist.github.com/jonnyreeves/2474026
2021-05-09 23:47:42