Javascript-function-constructors
提供:Dev Guides
JavaScript-Function()コンストラクター
_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>