Sunil Patel
Sunil Patel

Reputation: 265

Javascript anonymous function adding object to it

Can you explain what going on or some link to understand below code?

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;
}

Here type of app is function but where other object is assigned and then after return how to access these object

Upvotes: 0

Views: 165

Answers (1)

GibboK
GibboK

Reputation: 73928

A little explanation:

app is named function:

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

The mixin you see after are used to extend the properties on the original app object.

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

Below, this code define some properties on app.request you can look at docs for more infos.

The Object.defineProperties() method defines new or modifies existing properties directly on an object, returning the object.

In JS functions are objects so the can have their own properties (in this case request).

// 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 }
  })

The code initialize app object:

app.init();

Upvotes: 1

Related Questions