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

ave*_*net 67 javascript commonjs requirejs

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

有没有更好的方法来定义每个导出一个类的模块?如果没有,您如何命名模块导出的内容?导出类"Employee"的模块"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");
});
Run Code Online (Sandbox Code Playgroud)

jrb*_*rke 111

AMD的建议可以让你只返回一个值导出的对象.但请注意,这是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;
    };
});
Run Code Online (Sandbox Code Playgroud)

现在在另一个模块中,您可以使用Employee模块,如下所示:

define("main", ["Employee"], function (Employee) {
    var john = new Employee("John", "Smith");
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*ker 102

作为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;
});
Run Code Online (Sandbox Code Playgroud)

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

  • Alex,这个例子对我有帮助,它有很好的文档记录,可以提供你想要的例子:https://gist.github.com/jonnyreeves/2474026 (6认同)
  • 嗨,马克,你的帖子正是我要找的。除了一件事。是否可以为 Employee 对象定义一些不属于构造函数的字段?例如,具有位置属性和方法 positionToUpper,但不知何故在构造函数中定义该属性,而不是在员工 = new Employee ('john', 'smith'); 中。员工职位 = '经理'; 警报(员工。positionToUpper()); (2认同)