This section provides a tutorial example to compare 3 different ways of creating a function object: 'function' statement, 'function' operator, and 'Function()' constructor.
Now we know that there are 3 different ways to create a function:
Using the "function" declaration statement - Creating a function in the traditional way.
Using the "function" operator - Creating a function as a function literal on the fly while evaluating an expression.
Using the "Function()" constructor Creating a function in the object-oriented way.
The tutorial example below shows you how to create functions with 3 different ways:
// Function_Creation_Facilities.js
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// Creating a function with the "function" declaration statement
function convert_1(fahrenheit) {
println("Converting Fahrenheit = "+fahrenheit);
var celsius = (fahrenheit - 32.0 ) / 1.8;
println("Returning Celsius = "+celsius);
return celsius;
}
// Creating a function with the "function" operator
var convert_2 = function (fahrenheit) {
println("Converting Fahrenheit = "+fahrenheit);
var celsius = (fahrenheit - 32.0 ) / 1.8;
println("Returning Celsius = "+celsius);
return celsius;
};
// Creating a function with the "Function()" constrcutor
var convert_3 = new Function("fahrenheit",
"println(\"Converting Fahrenheit = \"+fahrenheit);"
+ "var celsius = (fahrenheit - 32.0 ) / 1.8;"
+ "println(\"Returning Celsius = \"+celsius);"
+ "return celsius;"
);
// Calling all 3
convert_1(70.0);
convert_2(70.0);
convert_3(70.0);
Run this JavaScript file with "jrunscript" in a command window, you will get: