Java Reference
In-Depth Information
This also means we can pass a function to another function's parameter. Take a look at the
following code:
function doSomething(fn) {
fn("Hello, World");
}
doSomething(alert);
This code defines a function called doSomething() , and it has a single parameter called fn . Inside
the function, the fn variable is used as a function; it's executed by using the fn identifier followed
by a pair of parentheses. The final line of code executes the doSomething() function and passes
the alert function as the parameter. When this code executes, an alert box displays the message
"Hello, World" .
passing Functions
trY it out
Let's rewrite the temperature converter page to use more functions. You can cut and paste some of
the code from ch4 _ example1.html , but the majority of this example will be new code. When you've
finished, save it as ch4 _ example2.html .
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4, Example 2</title>
</head>
<body>
<script>
function toCentigrade(degFahren) {
var degCent = 5 / 9 * (degFahren - 32);
document.write(degFahren + " Fahrenheit is " +
degCent + " Celsius.<br/>");
}
function toFahrenheit(degCent) {
var degFahren = 9 / 5 * degCent + 32;
document.write(degCent + " Celsius is " +
degFahren + " Fahrenheit.<br/>");
}
function convert(converter, temperature) {
converter(temperature);
}
convert(toFahrenheit, 23);
convert(toCentigrade, 75);
</script>
</body>
</html>
Search WWH ::




Custom Search