|
||||||||||||||||||||||
JS Tutorial
Part I - JS language
Part II- JS objects
Part III - Client-Side JS |
JavaScript Ch5 - Functions
A JavaScript function is simply a script that is sectioned off as a separate piece of code and given a name. Using this name, a script can then call this separate script to execute at any time and as often as it needs to. Functions are meant to serve a single purpose to help split up the many tasks that one script is designed to do. You can think of this process as telling JavaScript to perform this list of related instructions and tell you when it's done. Functions can receive values from their calling statements, call arguments. You can then use the arguments as variables within the statement block. The following code fragment shows the syntax for declaring a function:
function funcitonName ([argument1][...,argumentN]) {
[statements]
}
The keyword function is used to specify a name, functionName, which serves as the identifier for the
set of statements between the curly braces. Enclosed in the parentheses and separated by commas are the argument
names, which hold each value that a function receives. Technically, arguments are variables that are assigned to
literal values, or objects that are passed to the function by the calling statements. If you don't specify any
arguments, you must still include an empty set of parentheses to complete the declaration. The statements, which
are the core of the function, are executed each time the function is called. For better readability, statements
within the statement block are typically indented.
5.3 Where to declare functions You can declare function anywhere inside a <SCRIPT> block except within other functions or control structures. Keep in mind that just as different blocks of HTML document are loaded ahead of others, so are any scripts that are embedded in these HTML blocks. For this reason, it is recommended that you declare functions in a script that is embedded in the <HEAD> block of a document. Declaring all your functions here ensures that the functions are available if another script needs to them immediately.Example
<HTML>
<head>
<SCRIPT LANGUAGE="JavaScript">
function defaultColors(){
document.fgColor = "black";
document.bgColor = "white";
document.writeln("Inside of defaultColors()");
}
</SCRIPT>
</head>
<BODY>
<pre>
<script type="text/javascript">
document.writeln("Functions are scripts just waiting ro run");
defaultColors();
document.writeln("All done.");
</script>
</pre>
</BODY>
</HTML>
In the example in section above, the defaultColors() is called
from the second script block. This is an example of calling a function
that takes no arguments. When the HTML document is loaded, the function
is loaded into memory and "put on hold." The function is not executed
until the main script block calls it with the following statement: defaultColors();
At this point, program execution jumps immediately to the first line of the defaultColors() function. After executing all three
lines of code, the program jumps back to where it left off and finishes
what is left. This results in the same effect as if you had inserted all
the function's statements directly into that position of your code. Now that
a name is assigned to this function, all you need to do to run the same
statements is use its name again.
Setting up functions to accept arguments can be very useful. Doing so lets
you reuse the function in several ways while serving the same general purpose.
For example, you might want to create a function to be used many times
throughout your program; however, one of the values inside the function
might need to change each time the function is called. One way to solve this
problem without arguments is to use global variables that can be modified both
outside and inside the function. This can get confusing if you happen to use
the same variable names inside more that one function. The best thing to do is
set up the function to accept an argument for each value you want it to receive.
Example
<html>
<head>
<title>JavaScript Unleashed</title>
<script type="text/javascript">
function getBinary(anInteger){
var result = ""; //full 32-bit result
var shortResult = ""; //without leading zeros
for(var i=1; i <= 32; ++i){
if(anInteger & 1 == 1){
result = "1"+result;
shortResult = result;
}else{
result = "0" + result;
}
anInteger = anInteger >> 1;
}
return (shortResult);
}
</script>
</head>
<body>
<pre>
<script language="JavaScript">
var binaryString = "";
var x = 9;
binaryString = getBinary(x);
document.write("The number "+ x+ " in binary form is :");
document.write(binaryString);
document.write("<br/>");
x = 255;
binaryString = getBinary(x);
document.write("The number "+x+" in binary form is : ");
document.write(binaryString);
document.write("<br/>");
document.write("The value x is still equal to: "+x);
</script>
</pre>
</body>
</html>
When the function is called with a statement getBinary(x), the function
receives a copy of the value that is stored in x. This process is called
passing by value. The value is then assigned to the anInteger,
a variable local to the function. Notice that you don't need to declare
anInteger using the var keyword. JavaScript automatically
declares a new variable every time the function is called. You can then use
the variable throughout the statement block as a local variable. If the anInteger
changes value while inside the function, it doesn't affect the value of the variable x,
which was passed as an argument.
The last statement given in the getBinary() function is return(shortResult).
Just as a function can receives a value, it can also return a value. The
return statement returns a single value of the location in the
program that first called the function. Returning a value from a function works
in the same way as returning a value from an expression. The following statement
assigns the value returned by the function getBinary() to the variable binaryString:
binaryString = getBinary(x);In this case, the final value of shortResult ends up assigned to binaryString.
You can use functions that return values anywhere you use a normal expression. In the following example, a function is used in a condition expression of an if statement.
Example
<html>
<head>
<title>JavaScript Unleashed</title>
<script type="text/javascript">
function isPhone(aString){
var aChar = null;
var status = true;
if(aString.length != 13){
status = false;
}else{
for(var i = 0; i < 12;++i){
aChar = aString.charAt(i);
if(i == 0 && aChar == "("){
continue;
}else if( i == 4 && aChar == ")"){
continue;
}else if(i == 8 && aChar == "-"){
continue;
}else if(parseInt(aChar, 10) >= 0 && parseInt(aChar, 10) <= 9){
continue;
}else{
status = false;
break;
}
}
}
return status;
}
</script>
</head>
<body>
<pre>
<script language="JavaScript">
var userInput = "(800)555-1212";
if(isPhone(userInput)){
document.write("Thank yu for your phone number.");
document.write("<br/>I will have a representative get you");
document.write("<br/>more information");
}else{
document.write("Please re-enter your phone number");
document.write("<br/>using the format (###)###-###");
}
</script>
</pre>
</body> |
References(1) Aland Shalloway & James R. Trott, Design Patterns Explained, Second Edition.(2) Allen Holub, Holub on Patterns, Learning Design Patterns by Looking at Code (3) Eric Evans, Domain-Driven Design, Tackling complexity in the heart of software. Advertisement |
||||||||||||||||||||
|
||||||||||||||||||||||