Open In App

JavaScript Function() Constructor

The Javascript Function Constructor is used to create a new function object using the Function() constructor with the new operator. The Javascript Function Constructor creates a function that has a global scope. 

Syntax:



var variable = new Function(arg1, arg2..., Function Body)

Parameters:

Below are some examples that show the use of the Javascript function constructor.



Example 1: In this example, we will see the basic use of the Javascript function constructor.




<!DOCTYPE HTML>
<html>
<head>
    <script type="text/javascript">
        <!--
        var func = new Function("x", "y", "return x*y;");
        function geeks() {
           var result;
           result = func(10,20);
           document.write ( result );
        }
    </script>
</head>
  
<body>
    <h1 style="color:green">
        Geeks For Geeks
    </h1>
    <h3>Javascript function constructor</h3>
    <p>Click the following button to see the result</p>
  
    <input type="button" onclick="geeks()"value="Click Me">
  
</body>
</html>

Output:

Javascript function constructor

Example 2: In this example, we will create a Javascript constructor and print the values of the function.




<!DOCTYPE HTML>
<html>
<head>
    <script type="text/javascript">
        <!--
        var func = new Function("firstName", "lastName", 
                                "return firstName + ' ' + lastName + ' ' + firstName;");
        function geeks() {
           var result;
           result = func("Geeks","for");
           document.write ( result );
        }
    </script>
</head>
  
<body>
    <h1 style="color:green">
        Geeks For Geeks
    </h1>
    <h3>Javascript function constructor</h3>
    <p>Click the following button to see the result</p>
  
    <input type="button" onclick="geeks()"value="Click Me">
  
</body>
</html>

Output:

Javascript function constructor

We have a complete list of Javascript Functions, to check those please go through this Javascript Function Complete reference article.


Article Tags :