1

I'm diving into ExpressJS lib at /lib/router/index.js, it declares as below:

var proto = module.exports = function(options) {
  var opts = options || {};

  function router(req, res, next) {
    router.handle(req, res, next);
  }

  // mixin Router class functions
  setPrototypeOf(router, proto)

  router.params = {};
  router._params = [];
  router.caseSensitive = opts.caseSensitive;
  router.mergeParams = opts.mergeParams;
  router.strict = opts.strict;
  router.stack = [];

  return router;
};

proto.handle = function handle(req, res, out) {
  var self = this;

  debug('dispatching %s %s', req.method, req.url);

  var idx = 0;
  var protohost = getProtohost(req.url) || ''
  .........
}

I confused why they can not invoke directly, by a given way like that

return function(req, res, next) {
    handle(req, res, next);
}

it seems it is clearer and simpler.

Binh Le
  • 313
  • 3
  • 10
  • Is this information you are looking for? [https://www.thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/](https://www.thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/) or [https://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor](https://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor) – Nope May 17 '18 at 09:01

1 Answers1

0

Because they want to invoke it as a method, with access to all the properties of the router instance. Admittedly, they could have used

handle.call(router, req, res, next)

but if you already inherit it from your prototype then why not just call it as a method directly.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • yes, instead of invoking .call() for each of methods, inheriting prototype support to call all of those directly. The reason maybe just for convenient in coding style – Binh Le May 18 '18 at 00:37
  • What type of `proto` in this case `var proto = module.exports = function(options) `. As my understand, the `proto` is type of function, so I confused why they're able to declare ```proto.handle = function handle(req, res, out) {...}``` – Binh Le May 18 '18 at 03:53
  • @BinhLe `proto` is a (function) object, that's all what matters - any object can have properties and be inherited from. Admittedly, this is confusing, they could (should) have separated it between constructor function and normal prototype object.. However, the instance (`router`) is a function as well, so why not - they needed to inherit from `Function.prototype` anyway. – Bergi May 18 '18 at 11:07
  • all elements in JS are objects. I understand well. Thanks @Bergi – Binh Le May 18 '18 at 15:17