Search code examples
javascriptkoakoa-router

is new Router() and Router() identical in koa-router?


I saw the code that uses koa-router as below.

const Router = require('koa-router')

const routerWithoutNew = Router()

I thought it was an error, but I was surprised to see it working properly.

const Router = require('koa-router')

const routerWithNew = new Router()

and, it works fine, too.

what is difference between routerWithoutNew and routerWithNew?


Solution

  • They are treated identically due to the following line in the Koa Router source code:

    if (!(this instanceof Router)) return new Router(opts);
    

    (from https://github.com/koajs/router/blob/56735f009768e32cce89af60337e7e2a8d6bbbc4/lib/router.js#L51)