Why is Router used as a normal function instead of a constructor in express 4.x?

I am a newbie trying to understand Express 4.x routing and I am reading their manual at: http://expressjs.com/guide/routing.html

The last paragraph says the following:

The express.Router class can be used to create modular mountable route handlers. The Router Instance is a complete middleware and routing system

and accompanying code:

var express = require('express');
var router = express.Router();

      

Why is this constructor express.Router

called a regular function without an operator new

? They say it is a class in the documentation, they named it according to javascript style (first letter on first line), but they (and all other examples on the web) use it like a normal function.

+3


source to share


1 answer


Some people like to maintain a functional style in addition to the traditional piece. This is done by adding a simple check, such as at the top of the function:

function Router() {
  if (!(this instanceof Router))
    return new Router();

  // ...
}

      



This allows you to support both types of calls (with new

and without).

+5


source







All Articles