简体   繁体   中英

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.

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?
  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.

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

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.

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