Using the Function Constructor

This section provides a tutorial example on how to define new functions with the Function object type constructor.

JavaScript provides Function as a built-in object type. The constructor of the Function type has the following calling signature:

new Function("arg_1", "arg_2", ..., "function_body");

where the last parameter is a list o statements to form the body of the new function, and all other parameters are names of parameters of the new function.

The tutorial example below shows you how to define new functions with the Function object type constructor:

// Function_Constructor.js
// Copyright (c) 2013 by Dr. Herong Yang,

// Defining a new function with no parameters
   var hello = new Function(
      "println(\"Hello World!\");"

// Calling the function

// Defining a new function with one parameter
   var f2c = new Function("fahrenheit",
      "println(\"Converting Fahrenheit = \"+fahrenheit);"
      + "var celsius = (fahrenheit - 32.0 ) / 1.8;"
      + "println(\"Returning Celsius = \"+celsius);"
      + "return celsius;"

// Calling the function
   var received = f2c(212.0);
   println("Received Celsius = "+received);

Run this JavaScript file with "jrunscript" in a command window, you will get:

Hello World!
Converting Fahrenheit = 212
Returning Celsius = 100
Received Celsius = 100

Conclusion: The Function object type constructor works. But it is very hard to use, mainly because the statements of the new function must be entered as a single string literal. All quotes in those statements must be escaped with backslashes (\). It is still better to use the traditional way to define new functions using the "function" statements.

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

Using Functions as "Function" Objects

 Functions Are Objects of the "Function" Type

Using the Function Constructor

 Function Object Inherited Properties and Methods

 Function Object Instance Properties

 Creating Function Objects with "function" Statements

 Creating Function Objects with the "function" Operator

 Comparing 3 Ways of Creating Functions

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications


 PDF Printing Version