Ruslan Plastun
Ruslan Plastun

Reputation: 2254

Node.js modules VS IIFE functions' scope

So I have this code below with IIFE function. My function MinWrite looks for glVal outside of its scope (it was declared inside IIFE function so it has to look to the outer scope) and successfully finds glVal:

//test.js

var glVal = 3;

var Stuff = (function() {
    return {
        MinWrite: function() {
            console.log(glVal - 2);
        }
    }
})();

Stuff.MinWrite(); // returns 1

But when I have this situation:

test2.js

var glVal = 3;

var Stuff = require('./test1');

Stuff.MinWrite(); // returns "glVal is not defined"

test1.js

module.exports = {
    MinWrite: function() {
        console.log(glVal - 2);
    }
};

It returns error: "glVal is not defined". As far as I know when we require a module the module wrapping happens and wraps the code in module (test1.js) inside IIFE. So require is kind of "equal" to IIFE declaring. So why my code doesn't work in the second case?

Upvotes: 1

Views: 424

Answers (1)

Quentin
Quentin

Reputation: 943510

The scopes that a function has access to depend on where the function is declared, not where the function is called.

The two JS modules are different scopes. The function you create in test2 doesn't have access to any variables declared in test1.

requireing a module makes its exports available in test1, but it doesn't change which scopes it has access to.

If you want to use data from test1 in the exported function, you'll need to change that function to accept an argument and then pass it.

Upvotes: 4

Related Questions