Jeril Sebastian
Jeril Sebastian

Reputation: 853

Cant understand this Express JS source snippet

I was trying to understand Express JS source and this is the main module where express is exported

module.exports = createApplication;


function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  // expose the prototype that will get set on requests
  app.request = Object.create(req, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })

  // expose the prototype that will get set on responses
  app.response = Object.create(res, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })

  app.init();
  return app;
}

I am confused about this piece of code

  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

The variable app is assigned and used inside the function at the same time. How can this work? There is no definition of an app anywhere else. Find the real source here.

Upvotes: 1

Views: 56

Answers (1)

jfriend00
jfriend00

Reputation: 707158

The function is created and assigned to the app variable. That's a normal function expression assignment.

Then, the two mixin() lines add methods to the app function. So, after calling those functions, it has things like app.handle() and app.init().

Then, two more properties app.request and app.response are added.

Then, app.init() is called.

Then, sometime later the app function is called (when an http request arrives) and when it is called, it calls app.handle() which is just calling a function that is a property of itself. That's all legit. It would be similar to calling this.handle() in a more traditional object.

Here's a little demo of the part that seems to have you most confused:

var test = function() {
    test.doSomething();
}

test.doSomething = function() {
    console.log("doSomething");
}

test();    // causes test.doSomething() to get called

Upvotes: 2

Related Questions