Reputation: 238
I want to call function from variable name. My code is in react.js
Function to be called > authentication.signIn()
My code as follows
var authentication = require('authentication.js');
let controller = "authentication";
let operationId = "signIn";
const data = controller.operationId();
Here controller and operationId is dynamic. They will change in the next loop. For an example in the next loop the values of operationId is signOut and controller is authentication. Then function call to const data is as follows
const data = authentication.signOut();
but here the error comes: controller.operationId is not a function.
Upvotes: 2
Views: 1490
Reputation: 26165
you need to have an object to store your controllers and call things from
eg:
const controllers = {}
controllers.authentication = require('authentication')
// more controllers...
// later
const method = 'signIn', controller = 'authentication'
controllers[controller][method]()
same can work for stuff like global object or whatever. you can also wrap this into a function
eg very quickly
controller = (name, method, ...args) =>{
if (!controllers[name]){
throw `Oh no, unknown controller ${name}`
return
}
controllers[name][method](...args)
}
Upvotes: 2