Cannot reference objects defined in other files in express

I am making an application using the express framework of node.js. I have to use OOP features like inheritance in my application.

I created a simple class in routes/model folder.

exports.Rectangle = function(x,y)
{
    this.x = x;
    this.y = y; 
}

Rectangle.prototype.getArea = function()
{
    return (this.x * this.y);
}

Rectangle.prototype.toString = function()
{
    var tmp = "Rectangle " + this.x + " : " + this.y;

    return tmp;
}

My routes/index.js is like this:

exports.index = function(req, res){

var RectangleClass = require('./model/Rectangle.js');


var rect1 = new RectangleClass.Rectangle(4,6);


console.log(rect1.getArea());
console.log("Rect: " + rect1);

res.send("hello");

};

When I run the app I get the error: 500 ReferenceError: Rectangle is not defined The error is shown at the Rectangle.prototype.getArea = function() line in routes/model/Rectangle.js

However, if I copy paste the Rectangle class structure in my index.js file, then it is all working. But I have many classes and I do not want to define them all in one file. How can I reference objects defined in other files?

This is the problem in your initial setup:

exports.Rectangle = function(x, y) {
  ...
}
Rectangle.prototype.getArea = ...

exports.Rectangle doesn't magically create a variable called Rectangle in the current module, hence the undefined error when you try to use Rectangle.prototype.

There are a couple of solutions:

// one solution
var Rectangle = exports.Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...

// another solution
var Rectangle = function(x, y) { ... }
Rectangle.prototype.getArea = ...
exports = Rectangle;

// yet another solution
exports.Rectangle = function(x, y) { ... }
exports.Rectangle.prototype.getArea = ...

Or the one you found out yourself, although creating such a factory function isn't really necessary :)

This suddenly occurred to me. I used a getter method to create and return a Rectangle object. The following changes were made in Rectangle.js.

exports.getRectangle = function(x,y)
{
    var r = new Rectangle(x,y);

    return r;
}



Rectangle = function(x,y)
{
    this.x = x;
    this.y = y; 
}

The other methods were left unchanged.

In my index.js file, instead of

var r = new RectangleClass.Rectangle(6,4);

I used

var r = RectangleClass.getRectangle(6,4);