HTML and CSS Reference
In-Depth Information
Important This is also the most appropriate way to create your own aggregates of data
and behavior (objects) by using an explicit constructor without the need to use the new
operator. In this way, you get very close to object-oriented components in JavaScript.
Having fun with callback functions
Callbacks are just functions passed as an argument. Code that receives a callback function can call the
calling code back when appropriate. For example, suppose you have a generic function that holds a
collection of numbers. At various times you need to loop over the collection and perform different
operations, such as sum and multiplication. Should you really define two distinct (but fairly repetitive)
functions, as shown below?
function sumAllNumbers() {
// STEP 1: COLLECT INPUT DATA
var numbers = new Array();
for (var i = 0; i < arguments.length; i++) {
numbers.push(arguments[i]);
}
// STEP 2: PERFORM OPERATION
var result = 0;
for (var i = 0; i < numbers.length; i++) {
result += numbers[i];
}
// STEP 3: DISPLAY RESULTS
alert("SUM result is: " + result);
}
function multiplyAllNumbers() {
// STEP 1: COLLECT INPUT DATA
for (var i = 0; i < arguments.length; i++)
numbers.push(arguments[i]);
// STEP 2: PERFORM OPERATION
var result = 1;
for (var i = 0; i < numbers.length; i++) {
result *= numbers[i];
}
// STEP 3: DISPLAY RESULTS
alert("MULTIPLICATION result is: " + result);
}
Search WWH ::




Custom Search