0

Another post here explains that "Node wraps module's code into a function", and gave an explanation "https://nodejs.org/api/modules.html#modules_the_module_wrapper"

But I am still confused, I have following snippet:

var n = 'my'
module.a='k'
console.log(module.a);
console.log(module.n);

Using nodejs, it prints out

k
undefined

Question: if script level variables like 'n' is binded to function scope of nodejs "module", why 'module.n' doesn't exist?

Thanks.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

2

If you place your code and the wrapper function in the same picture, you'll get it:

(function (exports, require, module, __filename, __dirname) {
    var n = 'my'
    module.a='k'
    console.log(module.a); // k
    console.log(module.n); // undefined
});

you see that module.n is undefined because there's no code line that would set a value for it.

There's no magic that would cause "script level variables like 'n' get bound to 'module'".

pspi
  • 11,189
  • 1
  • 20
  • 18