简体   繁体   中英

Access dynamic function name in node.js

I have a js file that exports a function myFunction . Then, I have another function defined outside the exported module. How can I access it dynamically by its name?

I'm trying in this way but it doesn't work:

exports.myFunction = () => {
    let functionName = 'helperFunction';
    global[functionName]();
}

const helperFunction = () => {
    console.log('helperFunction invoked');
}

I'm trying with the global scope global[functionName](); , but doesn't work. What is the scope of the helper function?

The reason why helperFunction is outside the export is because I export multiple functions in the same file that call helperFunction.

TLDR: Use eval .

Hi there,

I tell you one thing about hoisting and then answer your question.

Now that you have defined your helperFunction after the export, it might cause a problem because of a JS behaviour called hoisting . The declaration of helperFunction is recognized in myFunction , but not the initialization. That will give you the following error:

ReferenceError: Cannot access 'helperFunction' before initialization

So, just move the helperFunction to the top of the file.

Now, to the actual answer. As you might have realized your helperFunction is actually in scope and you can call it. To do this, you need to evaluate the string: helperFunction() . You can use the following snippet:

console.log('hi');
let functionName = 'helperFunction';
eval(`${functionName}()`);
console.log('bye');

Bonus : what you are actually doing with your code is creating an array with one string element and call that array. That, of course, throws the following error:

TypeError: [functionName] is not a function

Theoretically speaking, you can make it work with global.

global.helperFunction = () => {
    console.log('helperFunction invoked');
}

const myFunction = () => {
    let functionName = 'helperFunction';
    global[functionName]();
}

Whether or not this is a good idea... well, that's an entirely different discussion. I don't know any details, but using Classes is usually the way to go in these cases.

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