Earlier, we saw that the () operator is used to invoke a function. Before a function can be invoked, however, it must be defined (except for those that are predefined by JavaScript); the function statement is used to define a new function. It has the following syntax:
function funcname([arg1 [,arg2 [..., argn]]]) { statements }
funcname is the name of the function that is being defined. This must be a literal name, not a string or an expression. arg1, arg2, and so on to argn are a comma-separated list of any number (including zero) of argument names for the function. These are also literal names, not strings or expressions. These names can be used as variables within the body of the function; when the function is executed, they will be assigned the values specified in the function call expression.
The function statement differs from statements like the while and for loops. In those loops, the body of the loop is a single statement, which can be a single primitive statement or a block of statements enclosed in curly braces. For the function statement, however, curly braces are a required part of the syntax, and any number of JavaScript statements may be contained within. Even if the body of a function consists of only a single statement, the curly braces must still be used. Here are some example function definitions:
function welcome() { alert("Welcome to my home page!"); } function print(msg) { document.write(msg, "<br>"); } function hypotenuse(x, y) { return Math.sqrt(x*x + y*y); // return is documented below } function factorial(n) { // a recursive function if (n <=index.html 1) return 1; else return n * factorial(n - 1); }
The most important way that the function statement differs from other statements is that the statements that form the body of the function are not executed. Instead, they are stored as the definition of a new function named funcname, and may be executed at any later time with the () function call operator.
We'll learn more about functions in Chapter 6, Functions.
file: /Techref/language/java/SCRIPT/definitive/ch05_11.htm, 6KB, , updated: 2019/10/14 15:00, local time: 2024/11/30 02:52,
18.216.70.205:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://massmind.ecomorder.com/techref/language/java/SCRIPT/definitive/ch05_11.htm"> [Chapter 5] 5.11 function</A> |
Did you find what you needed? |
Welcome to ecomorder.com! |
Welcome to massmind.ecomorder.com! |
.