Search code examples
javascriptnode.jsexpressurl-routing

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


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

In the last paragraph it says following:

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

and accompanying code is:

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

Why is this express.Router constructor called like ordinary function without the new operator? They say in documentation it's a class, they named it according to javascript style (capital first letter) but they (and all other examples online) use it as an ordinary function.


Solution

  • Some people like to support the functional style in addition to traditional instantiation. This is done by adding a simple check like this at the top of the function:

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

    This allows the support of both types of invocations (with new and without).