简体   繁体   中英

Context in Node.js module - How to access functions with reflection?

Can anyone tell me, in which context functions are put, when created globally in modules?

I try to access functions via reflection. A simplified approach is shown below.

leaf.js:

function GlobalLeafFn(){
  console.log("2");
}

console.log("Fn in Leaf via this" + this["GlobalLeafFn"]);
console.log("Fn in Leaf via global" + global["GlobalLeafFn"]);

When executed directly with node leaf.js the function can be found.

But when including the module in another script with

require("./leaf.js");

they are not found.

I already realized, that best practice is to use custom namespaces. But for curiosity I want to know: where are the functions referenced?

Thanks!

Node.js is a bit different from browser. Node.js has by default modules, every file is a module. Everything defined in the file as in your example, is private to that module. So you don't need namespaces in Node.js, because they are implicitly given via the module system.

in a Node.js module you have following scopes:

the default private scope

Here goes everything defined outside of a function with var or a function statement. It is the so called context.

the global scope

if you define something without var or assign it to a property on the global object. Also all built in types such as Array, Object, etc are here.

the export scope

everything defined with module.exports = or exports.foo = goes to this scope. this is what a user of the module can access from the outside. the public part. Initially the this variable in the module is bound to module.exports

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM