JavaScript calls the implementation of the function through a string

  • 2020-05-17 04:47:25
  • OfStack

This article illustrates the implementation of JavaScript by calling a function through a string. Share with you for your reference. The specific analysis is as follows:

In JavaScript, we can call the function based on the string of the function name, so we can implement the dynamic function call, we only need to pass the name of a function to call the function.

var strFun = "someFunction"; //Name of the function to be called
var strParam = "this is the parameter"; //Parameters to be passed in function
//Create the function
var fn = window[strFun];
//Call the function
fn(strParam);


The following is a detailed invocation instance
<input type="text" id="functionName" name="functionName" size="20" value="fnFooBar">
    <input type="text" id="functionParam" name="functionParam" size="30" value="Happy New Year.!!">
    <input type="button" style="font-weight:bold" value="Call" onclick="javascript:call();">
    <br>
    <pre>
    function fnFooBar(strVal) {
            alert(strVal);
            return 1;
        }
   </pre>
<br>
<script>
function fnFooBar(strVal) {
    alert(strVal);
    return 1;
}
function call() {
    var strFunctionName = document.getElementById("functionName").value;
    var strFunctionParam = document.getElementById("functionParam").value;
    var fn = window[strFunctionName]
    var ret = fn(strFunctionParam);
}
</script>

I hope this article is helpful to you in javascript programming.


Related articles: