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>

輸出

javascript_functions.htm
廣告