Home >Web Front-end >JS Tutorial >Tutorial on using the Function() function in JavaScript_Basic knowledge
The function statement is not the only way to define a new function, and you can define your function dynamically using the Function() constructor using operators.
Note: This is a term for object-oriented programming. You may feel a bit unaccustomed to it the first time, but there is no problem here.
Grammar
The following is the syntax for using the new operator to create a constructor using Function().
<script type="text/javascript"> <!-- var variablename = new Function(Arg1, Arg2..., "Function Body"); //--> </script>
Function() function constructor expects any number of string parameters. The last parameter is the function body - it can contain arbitrary JavaScript statements, separated from each other by semicolons.
Please note that the Function() construct does not pass any parameters, specify a name to create the function for it. An unnamed function created using the Function() constructor is called an anonymous function.
Example:
The following is an example of creating a function:
<script type="text/javascript"> <!-- var func = new Function("x", "y", "return x*y;"); //--> </script>
This line of code creates a new function that is more or less equivalent to the syntax of the defined function:
<script type="text/javascript"> <!-- function f(x, y){ return x*y; } //--> </script>
This means you can call the above function as follows:
<script type="text/javascript"> <!-- func(10,20); // This will produce 200 //--> </script>