JavaScript Tutorials - Herong's Tutorial Examples - Version 2.21, by Dr. Herong Yang
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:
function [function_name](parameter_1, parameter_2, ...) { statement_1; statement_2; ... return return_expression };
The "function" operator actually does only 2 things:
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) 2013 by Dr. Herong Yang, 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:
Banana Orange Hello Converting Fahrenheit = 70 Returning Celsius = 21.11111111111111
Table of Contents
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
Creating, Accessing, and Manipulating Arrays
Defining and Calling Functions
Web Browser Supporting JavaScript
Server-Side and Client-Side Web Scripting
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