0

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?

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
Ruslan Plastun
  • 1,224
  • 2
  • 9
  • 25

1 Answers1

4

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • But what about this: (https://stackoverflow.com/questions/28955047/why-does-a-module-level-return-statement-work-in-node-js/28955050#28955050). The first answer says that: "The modules are wrapped by Node.js within a function"? Or right here the same: (https://stackoverflow.com/questions/15406062/in-what-scope-are-module-variables-stored-in-node-js) – Ruslan Plastun Jun 18 '18 at 08:04
  • @PetroKoval — What about that? It doesn't, in any way, contradict anything I said in this answer. – Quentin Jun 18 '18 at 08:19
  • So when we "require" the module's code is wrapped in a function and executed, but this same code is still situated in a completely different and separate scope, right? – Ruslan Plastun Jun 18 '18 at 08:23