简体   繁体   English

获取Node.js中一个文件的所有函数

[英]Obtain all functions in a file in Node.js

I have some functions inside a file.我在文件中有一些函数。 I'm trying to obtain all functions in that file, from within that file.我正在尝试从该文件中获取该文件中的所有函数。 Normally, all functions are in the window object, but I'm using Node.js, which does not seem to have a window object. Normally, all functions are in the window object, but I'm using Node.js, which does not seem to have a window object.

Say I have something along the lines of the following in a file:假设我在文件中有以下内容:

function foo() {}
function bar() {}

then:然后:

  1. Are the functions saved in some global object?函数是否保存在一些全局object中?
  2. If not, how can I access these functions without knowing their names?如果没有,我如何在不知道它们的名字的情况下访问这些功能? Can I iterate through all existing functions and obtain them in such a way?我可以遍历所有现有功能并以这种方式获取它们吗?

You want to get access to the current scope object but it's impossible in JavaScript.您想访问当前的 scope object 但在 JavaScript 中是不可能的。

The following is a common pattern下面是一个常见的模式

var foo = exports.foo = function() {
    // ...
}

This way its written to exports and you can access it locally as foo这样它就被写入了exports ,您可以在本地以foo的身份访问它

Your functions are wrapped in a closure.你的函数被包裹在一个闭包中。 Remember, node wraps file modules within something like this请记住,节点将文件模块包装在这样的东西中

var module = { exports: {}};
(function(module, exports){
    // your file module content
})(module, module.exports);

They are locals.他们是当地人。 Assign functions to an object, exports or global to enumerate them.将函数分配给 object、 exportsglobal以枚举它们。

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

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