根据 Node.js 手册:
如果希望模块导出的根是一个函数(如 一个构造函数) ,或者如果你想导出一个完整的对象 赋值,而不是一次构建一个属性,将其赋值给 出口而不是出口。
给出的例子是:
// 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());
我的问题是: 为什么这个例子不使用正方形作为一个对象?下面的内容是否有效,是否使示例更加“面向对象”?
var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());