HTML and CSS Reference
In-Depth Information
that.name = "SUM";
that.execute = function (numbers) {
var result = 0;
for (var i = 0; i < numbers.length; i++) {
result += numbers[i];
}
return result;
};
return that;
}
var Multiplication = function () {
var that = {};
that.name = "MULTIPLICATION";
that.execute = function (numbers) {
var result = 1;
for (var i = 0; i < numbers.length; i++) {
result *= numbers[i];
}
return result;
};
return that;
}
Finally, the code to invoke operations looks like what follows:
handleNumbers(new Sum(), 1, 2, 3, 4);
handleNumbers(new Multiplication(), 1, 2, 3, 4);
Using objects in lieu of functions gives you a lot more programming power because you are not
limited in any way in terms of the contract that you can support.
Anonymous Functions
So far, this chapter has focused mostly on named functions. What about unnamed functions
(anonymous functions), instead? In JavaScript, anonymous functions are the pillar of functional
programming. An anonymous function is a direct offshoot of lambda calculus or, if you prefer, a
language adaptation of old-fashioned function pointers. Here's a simple example of an anonymous
function:
function(x, y) {
return x + y;
}
The only difference between a regular function and an anonymous function is in the name (or lack
thereof).
Search WWH ::




Custom Search