∟Creating Function Objects with the "function" Operator
This section provides a tutorial example on how to create a Function object with a 'function' operator. A function defined with a 'function' operator is also called function literal or expression.
By definition, a function is an object instance of the Function object type.
In previous sections, we learned how to create a function with the Function constructor.
A function can also be created with the "function" operator:
The "function" operator actually does only 2 things:
Created a Function object.
Named the Function object with "function_name". If no name is provided, the Function object will have no name.
A function defined with the "function" operator is also called a function literal or a function expression.
A function defined with the "function" operator should be assigned to a variable. Otherwise, it will be accessible
outside the expression where the operator is used.
The tutorial example below shows you how to use the "function" operator to create a Function object:
// Function_Operator.js
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// A function with no reference variable and no name
function() { println('Apple'); };
// no way to call it outside the expression
// call it as part of the expression is ok
(function() { println('Banana'); }).call(this);
// A function with a reference variable and no name
var orange = function() { println('Orange'); };
orange();
// A function with a reference variable and a name
var hello = function allo() { println('Hello'); };
hello();
// allo(); // calling by function name is not allowed!
// A function with a reference variable, a parameter and no name
var f2c = function (fahrenheit) {
println("Converting Fahrenheit = "+fahrenheit);
var celsius = (fahrenheit - 32.0 ) / 1.8;
println("Returning Celsius = "+celsius);
return celsius;
};
f2c(70.0);
Run this JavaScript file with "jrunscript" in a command window, you will get: