According to the Node.js manual:
If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.
The example given is:
// file: square.js
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
and used like this:
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());
My question: why does the example not use square as an object? Is the following valid and does it make the example more "object oriented"?
var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());
This question is related to
javascript
node.js
commonjs
The example code is:
in main
square(width,function (data)
{
console.log(data.squareVal);
});
using the following may works
exports.square = function(width,callback)
{
var aa = new Object();
callback(aa.squareVal = width * width);
}
This question doesn't really have anything to do with how require()
works. Basically, whatever you set module.exports
to in your module will be returned from the require()
call for it.
This would be equivalent to:
var square = function(width) {
return {
area: function() {
return width * width;
}
};
}
There is no need for the new
keyword when calling square
. You aren't returning the function instance itself from square
, you are returning a new object at the end. Therefore, you can simply call this function directly.
For more intricate arguments around new
, check this out: Is JavaScript's "new" keyword considered harmful?
At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.
This way actually you are creating a new function, as we created using JS on Web Browser environment for example.
Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor
In my opinion, some of the node.js examples are quite contrived.
You might expect to see something more like this in the real world
// square.js
function Square(width) {
if (!(this instanceof Square)) {
return new Square(width);
}
this.width = width;
};
Square.prototype.area = function area() {
return Math.pow(this.width, 2);
};
module.exports = Square;
Usage
var Square = require("./square");
// you can use `new` keyword
var s = new Square(5);
s.area(); // 25
// or you can skip it!
var s2 = Square(10);
s2.area(); // 100
For the ES6 people
class Square {
constructor(width) {
this.width = width;
}
area() {
return Math.pow(this.width, 2);
}
}
export default Square;
Using it in ES6
import Square from "./square";
// ...
When using a class, you must use the new
keyword to instatiate it. Everything else stays the same.
Source: Stackoverflow.com