Question

If I'm defining a module with the following code:

module.exports = Person;

function Person (name) {
    this.name = name;
};

How come when I require this file the first line doesn't return a ReferenceError, since I haven't defined Person yet?

Was it helpful?

Solution

The entire JS file is parsed FIRST before anything is executed. Thus, the function Person() exists from the parse step before the line module.exports = Person is actually executed.

So, when you do it your way:

// Person already exists and is a function
module.exports = Person;

function Person (name) {
    this.name = name;
};

everything works fine because the definition of Person() is picked up in the parse stage before execution.

But, if you did it like this:

// Person exists, but has no value yet (will be undefined)
module.exports = Person;

var Person = function(name) {
    this.name = name;
};

It would not work because the Person variable would not yet have been assigned when the module.exports = Person line executes. This is one of the main differences between these two methods of defining a function (the timing of when the function is actually available).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top