function 语句不是定义新函数的唯一方法;您可以使用 Function()构造函数以及 new 运算符动态地定义函数。
注意 - 构造函数是面向对象编程中的术语。
以下是使用 Function()构造函数以及 new 运算符创建函数的语法。
<script type="text/javascript"> <!-- var variablename=new Function(Arg1, Arg2..., "Function Body"); //--> </script>
Function()构造函数需要任意数量的字符串参数,最后一个参数是函数的主体–它可以包含任意JavaScript语句,以(;)分号分隔。
请注意,没有向 Function()构造函数传递任何为其创建的函数指定名称的参数。用 Function()构造函数创建的未命名函数称为匿名函数。
请尝试以下示例。
<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>
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)