目录

JavaScript Function( ) Constructor

function语句不是定义新函数的唯一方法; 您可以使用Function()构造函数和new运算符动态定义函数。

Note - 构造函数是面向对象编程的术语。 你可能第一次感到不舒服,这没关系。

语法 (Syntax)

以下是使用Function( )构造函数和new运算符创建函数的语法。

<script type="text/javascript">
   <!--
      var variablename = new Function(Arg1, Arg2..., "Function Body");
   //-->
</script>

Function()构造函数需要任意数量的字符串参数。 最后一个参数是函数体 - 它可以包含任意JavaScript语句,用分号相互分隔。

请注意, Function()构造函数未传递任何指定其创建的函数名称的参数。 使用Function()构造函数创建的unnamed函数称为anonymous函数。

例子 (Example)

请尝试以下示例。

<html>
   <head>
      <script type="text/javascript">
         <!--
            var func = new Function("x", "y", "return x*y;");
            function secondFunction(){
               var result;
               result = func(10,20);
               document.write ( result );
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type="button" onclick="secondFunction()" value="Call Function">
      </form>
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>

输出 (Output)

新页面打开
↑回到顶部↑
WIKI教程 @2018