JavaScript Tutorials - Herong's Tutorial Examples - Version 2.21, by Dr. Herong Yang
Comparing 3 Ways of Creating Functions
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:
The tutorial example below shows you how to create functions with 3 different ways:
// Function_Creation_Facilities.js // Copyright (c) 2013 by Dr. Herong Yang, 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:
Converting Fahrenheit = 70 Returning Celsius = 21.11111111111111 Converting Fahrenheit = 70 Returning Celsius = 21.11111111111111 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