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.