user3584659 user3584659 - 3 months ago 7
Node.js Question

What is the context of functions in file by nodejs?

What is the context of functions in files by nodejs?
If I need exports function I just write

module.exports = function () {};
or
module.someFunction = function () {};


But what context has function without module?

function someFunction () {};
console.log(module); // not someFunction
console.log(module.exports); // not someFunction


P.S. Where can I see some list of declared functions in this file? In browser I have
window
. In nodejs I have
global
,
module
,
module.exports
, but not one of its haven't the declared functions.

Answer

But what context has function without module?

Same as normal JavaScript functions. In strict mode, context will be undefined

(function() {
  'use strict';
  console.log(this === undefined);
})();
// true

and in sloppy mode (non-strict mode) global object.

(function() {
  console.log(this === global);
})();
// true

Note: If you are wondering what thisrefers to, in the module level, it will be the exports object. Detailed explanation can be found in this answer.

Comments