简体   繁体   中英

How to store reference to function?

Given a list of functions, I wish the user to be able to select any of the functions to run at startup. How can this be done so that the user can "save" their choice of function to run the next time the code is run ie what would function runSelectedFunction (below) look like since you can't "save" a javascript function to file? Also, assume the list of potential functions is extensible.

 const first = ()=>{ console.log('first'); } const second = ()=>{ console.log('second'); } const third = ()=>{ console.log('third'); } loadUserSelectedFunctionFromDB() .then(runSelectedFunction) 

To be clear, the goal is to persist the user choice even if the code stops executing and is restarted. Normally, this would be done by storing a value in a database but the question is how to store a reference to a function in a database given an extensible set of functions?

Use a map like this:

const m = {
  first, second, third
};

let selectFuncName = "first"; // from user selection, maybe click a button
let selectFunc = m[selectFuncName];

loadUserSelectedFunctionFromDB()
.then(runSelectedFunction)

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