Based on your question, you want to define and call global functions with a name defined at runtime.
To do that, you can use the indexer on the
window
object to get or set a global property with a constructed name:
const defineGlobalFunction = (r) => {
window[`funclk_${r}`] = () => {
alert(`Hi from function ${r}`);
};
};
const callGlobalFunction = (r) => {
const fn = window[`funclk_${r}`];
if (typeof fn === "function") {
fn();
} else {
console.error("Global function", r, "has not been defined");
}
};
Demo[
^]
NB: Whilst you could potentially use
eval
as suggested in solution 1, it can cause problems. See
Never use eval()! - JavaScript | MDN[
^] for details.