shortstuffsushi
shortstuffsushi

Reputation: 2330

How does putting 'module.exports = foo' work before foo is defined?

I won't claim that I'm terribly well versed in Node, or even Javascript, but I've seen several modules of the form

module.exports = foo;

function foo() {
  ...
}

Now, I could see this working perhaps in this case, but I'm really confused when that module returns a function that is excuted.

module.exports = bar();

function bar() {
  ...
}

What is this witchcraft?

Upvotes: 0

Views: 98

Answers (1)

Polity
Polity

Reputation: 15130

Functions are defined at parse time, assignments are assigned at runtime. See this article http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ for more.

In short, the compiler makes 2 passes. With the following code:

var a = x;
function x( ) { }

In the first pass, var a and function x are declared and available in a symbol table (or some other form depending on the interpreter) after which the compiler makes a second pass performing the assignment of function x as to var a. At this stage, at any point (but limited to the language rules), function x is known.

Upvotes: 5

Related Questions