This article describes the implementation method of JavaScript calling functions through strings. Share it for your reference. The specific analysis is as follows:
In JavaScript, we can call functions based on the string of function names, so that we can implement dynamic function calls, and we only need to pass the name of a function to call the function.
Copy the code as follows: 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);
Below is a detailed call example
Copy the code code as follows: <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 will be helpful to everyone's JavaScript programming.