根据 Node.js 手册:
如果您想要模块的导出根部是一个函数 (例如构造函数), 或者如果您想要在一个赋值操作中导出一个完整的对象而不是逐个属性地构建它,将其分配给 module.exports 而不是 exports。
给出了以下示例:
// file: square.js
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
并且可以像这样使用:
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());
我的问题是:为什么这个例子没有使用 square 作为一个对象?以下内容是否有效,并且能让这个例子更加“面向对象”?
var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());
square
重命名为Square
后,new square()
就不存在了。 - Sukimanew
关键字并组织我的模块来导出单个构造函数。我发现这可以使解决方案的可读性和概念化更容易。我一眼就能看出我打算使用什么样的结构。赞同你像我一样思考 ;) - Sukima