如何在Node.js中通过变量动态调用模块的子模块函数?
Hey there! I get what you're trying to do here—you want to use a variable to dynamically access a property on your abc module, right? The issue with your original code is that dot notation (. ) expects a literal property name, not a variable. Here's how to fix it:
The Fix: Use Bracket Notation
Instead of abc.x.someFunction(), you need to use square bracket notation to access the property using your variable x. This works because bracket notation lets you use variables or expressions to reference property names, unlike dot notation which requires a hardcoded name.
Here's your updated code:
var abc = require('./index') var x = "someModule"; abc[x].someFunction(); // This is equivalent to abc.someModule.someFunction()
Why This Works
When you write abc[x], JavaScript evaluates the value of x (which is "someModule" in this case) and uses that as the property name to look up on the abc object. So it's exactly the same as writing abc.someModule directly—just using a variable instead of a literal string.
Quick Check for Your Exported Module
Just make sure your ./index.js module is exporting the someModule property correctly. For example, it might look like this:
// index.js module.exports = { someModule: { someFunction: () => { console.log("Running someFunction!"); } } };
That's all there is to it—this will let you dynamically access the module property using your variable and call the function as intended.
内容的提问来源于stack exchange,提问作者user3762146

