0

Taken from: https://github.com/strongloop/express/blob/master/lib/express.js

function createApplication() {
  var app = function(req, res, next) { // app here is a function
    app.handle(req, res, next); // how is it that app can have properties? is this recursive?
  };

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

  app.request = { __proto__: req, app: app }; // property declaration
  app.response = { __proto__: res, app: app }; // property declaration again
  app.init();
  return app;
}

Would appreciate primary source links for legitimacy sirs!

geoyws
  • 3,326
  • 3
  • 35
  • 47
  • 7
    Because in JavaScript, a function *is* an object, and can have properties. – Cᴏʀʏ Oct 06 '14 at 19:42
  • The code shown is a bit of a hack to "add" a property without altering the underlying object, this is done via the [[prototype]] chain. (The same can be done with Object.create with a little more verbosity and a little more ES5-compliance.) – user2864740 Oct 06 '14 at 19:43
  • Yes, there are done [lots of odd things in express](http://stackoverflow.com/a/23628216/1048572) which [might better be done differently](http://stackoverflow.com/a/24811424/1048572) – Bergi Oct 07 '14 at 01:50

2 Answers2

4

All non-primitives in JavaScript are objects. This includes functions, arrays, RegExps, Dates, etc.

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

Okay this answers everything satisfactorily for me: http://jsfiddle.net/geoyws/4ebv4pbv/

var x = function () {
    alert(1); // alerts 1
    x.wtf = 2;
    x.ftw = 3;
    return x.ftw;
}

alert(x()); // alerts 3
geoyws
  • 3,326
  • 3
  • 35
  • 47