我有许多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");
});
发布于 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");
});
发布于 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中显示的模式。
https://stackoverflow.com/questions/4869530
复制相似问题