Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to call a function in javascript, that function's name includes a variable (r):
Example
function funclk_r(){
do something
}
How can I arrange name of function '
funclk_
' then (r) then ()?

What I have tried:

<script>
    var r=48;
        function 'funclk_'+r(){
            alert("hi");
        }
    </script>

Not working!
Posted
Updated 5-Mar-23 22:36pm

You can use the eval function in javascript to execute js code as a string

var r=48;
function funclk_48(){
  alert("48");
}
function funclk_49(){
  alert("49");
}
function funclk_50(){
  alert("50");
}

eval("funclk_"+r+"()");


fiddle here - JSFiddle - Code Playground[^]
 
Share this answer
 
Comments
Member 14819235 17-Mar-23 18:23pm    
Thnx
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:
JavaScript
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.
 
Share this answer
 
Comments
Member 14819235 17-Mar-23 18:23pm    
Thnx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900