简体   繁体   English

Node.js模块中的上下文-如何通过反射访问函数?

[英]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. 当直接用node leaf.js执行时,可以找到该函数。

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与浏览器有点不同。 Node.js has by default modules, every file is a module. Node.js默认具有模块,每个文件都是一个模块。 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. 因此,您不需要Node.js中的名称空间,因为它们是通过模块系统隐式指定的。

in a Node.js module you have following scopes: 在Node.js模块中,您具有以下作用域:

the default private scope 默认的私有范围

Here goes everything defined outside of a function with var or a function statement. 这里是使用var或function语句在函数外部定义的所有内容。 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. 如果您定义不带var或将其分配给global对象的属性。 Also all built in types such as Array, Object, etc are here. 同样,所有内置类型(例如Array,Object等)也在此处。

the export scope 出口范围

everything defined with module.exports = or exports.foo = goes to this scope. 具有定义的一切module.exports =exports.foo =进入此范围。 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 最初,模块中的this变量绑定到module.exports

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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