Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

JavaScript - The Function() Constructor (Javascript)

The function statement is not the only way to define a new function but also, you can define your function dynamically using Function( ) constructor along with the new operator.
Note: This is the terminology from Object Oriented Programming. You may not feel comfortable for the first time, which is OK.

Syntax:

Following is the syntax to create a function using Function( ) constructor along with the new operator.
<script type="text/javascript">
<!--
var variablename = new Function(Arg1, Arg2..., "Function Body");
//-->
</script>
The Function() constructor expects any number of string arguments. The last argument is the body of the function - it can contain arbitrary JavaScript statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions.

Example:

Here is an example of creating a function in this way:
<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 a function defined with the familiar syntax:
<script type="text/javascript">
<!--
function f(x, y){ 
   return x*y; 
}
//-->
</script>
It means you can call above function as follows:
<script type="text/javascript">
<!--
func(10,20); // This will produce 200
//-->
</script>