1
JavaScript 使用 Function() 构建函数
Posted by 撒得一地 on 2016年5月11日 in JavaScript教程
函数语句并不是唯一能够定义一个新函数的方法,您可以动态的使用 new 运算符以及 Function() 构建一个新函数。
请注意:构造函数是从面向对象编程的术语。在这里可能会引起歧义。
语法
以下是使用 new 运算符和 function() 构造新函数的语法。
<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>
1 Comment
好东西!!