最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What does the empty parentheses mean after 'require' declaration in Node.js? - Stack Overflow

programmeradmin3浏览0评论

In Node.js I see sometimes a declaration like this:

var App = require('express')();

What do the empty brackets '()' at the end mean?

I am suspecting the declaration above is equivalent to something like:

var Express = require('express');
var App = Express();

Is that right?

In Node.js I see sometimes a declaration like this:

var App = require('express')();

What do the empty brackets '()' at the end mean?

I am suspecting the declaration above is equivalent to something like:

var Express = require('express');
var App = Express();

Is that right?

Share edited May 20, 2016 at 16:27 user663031 asked May 20, 2016 at 15:57 eYeeYe 1,7332 gold badges29 silver badges60 bronze badges 3
  • You are correct. Require returns a function which is called using the (). – Tejas Kale Commented May 20, 2016 at 15:59
  • 1 Also check out this blog post : fredkschott./post/2014/06/require-and-the-module-system – Tejas Kale Commented May 20, 2016 at 16:01
  • Syntactically, by definition, the () could do only thing, which is to invoke a function. – user663031 Commented May 20, 2016 at 16:28
Add a ment  | 

2 Answers 2

Reset to default 8

As James already answered the module returns a function which is than invoked in this manner.

Here a simple code sample to make it easier understandable.

function a() {
    function b() {
        alert('Alert me!');
    }
    return b;
}
a()();
//alerts 'Alert me!'  

Essentially the express module is returning a function. The empty brackets call the function so now App is the result of the returned function.

发布评论

评论列表(0)

  1. 暂无评论