【问题标题】:RequireJS: How to define modules that contain a single "class"?RequireJS:如何定义包含单个“类”的模块?
【发布时间】:2011-06-19 15:56:51
【问题描述】:

我有许多 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");
});

【问题讨论】:

    标签: javascript commonjs requirejs


    【解决方案1】:

    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");
    });
    

    【讨论】:

    • 哇,@jrburke 先生的直接回答。 RequireJS自己! +1!
    【解决方案2】:

    作为 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;
    });
    

    事实上,这正是this example at requirejs.org 中显示的模式。

    【讨论】:

    • 嗨,马克,你的帖子正是我要找的。除了一件事。是否可以为 Employee 对象定义一些不属于构造函数的字段?例如有 position 属性和方法 positionToUpper,但以某种方式定义该属性不在构造函数中 employee = new Employee ('john', 'smith'); employee.position = '经理'; alert(employee.positionToUpper());
    • Alex,这个例子对我很有帮助,它有很好的文档记录,可能可以提供你正在寻找的例子:gist.github.com/jonnyreeves/2474026
    • @NathanPrather 这是一个很好的参考——cmets 帮助我从 java 背景翻译了
    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多