Nafiul Islam
Nafiul Islam

Reputation: 82590

Difference between initating an express object in nodejs?

I can use express in two ways, that is I can initialize it in two ways:

var app = express(); or var app = new express();

From the looks of things, both are calling a constructor, so is there really any difference between the two, I'm mainly asking performance wise, is there really any difference, because I seemed to have experienced none.

If there is no real difference how come every tutorial I've seen does it the first way and not the second way, because the second one seems to be clearer.

Upvotes: 1

Views: 71

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146154

In this case calling express() as a function is more correct.

https://github.com/visionmedia/express/blob/8a1e865e37016f279d957f04117007c36ac195e3/lib/express.js#L32

function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
}

This is basically a factory function, not a constructor. Using the new keyword will create an unnecessary object that will immediately be discarded since the createApplication returns an object, the automatic this that the new keyword creates is discarded (this is just how the JavaScript language works).

So the answer is both versions work fine, but using new is unnecessary here.

Upvotes: 3

Related Questions