首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >RequireJS:如何定义包含单个“类”的模块?

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

Stack Overflow用户
提问于 2011-02-02 08:23:39
回答 2查看 55K关注 0票数 68

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-03 02:19:29

AMD proposal允许您只返回导出对象的值。但请注意,这是AMD提案的一个功能,它只是一个应用编程接口提案,并将使其更难转换回常规的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");
});
票数 114
EN

Stack Overflow用户

发布于 2012-04-23 20:39:41

作为对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中显示的模式。

票数 106
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4869530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档