JavaScript通过字符串调用函数的实现方法

  本文实例讲述了JavaScript通过字符串调用函数的实现方法。分享给大家供大家参考。具体分析如下:

  JavaScript中我们可以把根据函数名的字符串来调用函数,这样我们就可以实现动态函数调用,只需要传递一个函数的名字即可调用该函数。

  

复制代码 代码如下:
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);

  下面是一个详细的调用实例

  

复制代码 代码如下:
<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>

  希望本文所述对大家的javascript程序设计有所帮助。