Monday, November 2, 2009

Section 8.3. Functions as Data










8.3. Functions as Data









The most important features of functions are that they can be defined and invoked, as shown in the previous section. Function definition and invocation are syntactic features of JavaScript and of most other programming languages. In JavaScript, however, functions are not only syntax but also data, which means that they can be assigned to variables, stored in the properties of objects or the elements of arrays, passed as arguments to functions, and so on.[*]

[*] This may not seem like a particularly interesting point unless you are familiar with languages such as Java, in which functions are part of a program but cannot be manipulated by the program.


To understand how functions can be JavaScript data as well as JavaScript syntax, consider this function definition:



function square(x) { return x*x; }



This definition creates a new function object and assigns it to the variable square. The name of a function is really immaterial; it is simply the name of a variable that refers to the function. The function can be assigned to another variable and still work the same way:



var a = square(4); // a contains the number 16
var b = square; // Now b refers to the same function that square does
var c = b(5); // c contains the number 25



Functions can also be assigned to object properties rather than global variables. When you do this, they're called methods:



var o = new Object;
o.square = function(x) { return x*x; } // function literal
y = o.square(16); // y equals 256



Functions don't even require names at all, as when they're assigned to array elements:



var a = new Array(3);
a[0] = function(x) { return x*x; }
a[1] = 20;
a[2] = a[0](a[1]); // a[2] contains 400



The function-invocation syntax in this last example looks strange, but it is still a legal use of the JavaScript () operator!


Example 8-2 is a detailed example of the things that can be done when functions are used as data.
It demonstrates how functions can be passed as arguments to other functions. This example may be a little tricky, but the comments explain what is going on; it is worth studying carefully.


Example 8-2. Using functions as data




// We define some simple functions here
function add(x,y) { return x + y; }
function subtract(x,y) { return x - y; }
function multiply(x,y) { return x * y; }
function divide(x,y) { return x / y; }

// Here's a function that takes one of the above functions
// as an argument and invokes it on two operands
function operate(operator, operand1, operand2)
{
return operator(operand1, operand2);
}

// We could invoke this function like this to compute the value (2+3) + (4*5):
var i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5));

// For the sake of the example, we implement the simple functions again, this time
// using function literals within an object literal;
var operators = {
add: function(x,y) { return x+y; },
subtract: function(x,y) { return x-y; },
multiply: function(x,y) { return x*y; },
divide: function(x,y) { return x/y; },
pow: Math.pow // Works for predefined functions too
};

// This function takes the name of an operator, looks up that operator
// in the object, and then invokes it on the supplied operands. Note
// the syntax used to invoke the operator function.
function operate2(op_name, operand1, operand2)
{
if (typeof operators[op_name] == "function")
return operators[op_name](operand1, operand2);
else throw "unknown operator";
}

// We could invoke this function as follows to compute
// the value ("hello" + " " + "world"):
var j = operate2("add", "hello", operate2("add", " ", "world"))
// Using the predefined Math.pow() function:
var k = operate2("pow", 10, 2)




If the preceding example does not convince you of the utility of being able to pass functions as arguments to other functions and otherwise treat functions as data values, consider the Array.sort() function. This function sorts the elements of an array. Because there are many possible orders to sort by (numerical order, alphabetical order, date order, ascending, descending, and so on), the sort() function optionally takes another function as an argument to tell it how to perform the sort. This function has a simple job: it takes two elements of the array, compares them, and then returns a value that specifies which element comes first. This function argument makes the Array.sort() method perfectly general and infinitely flexible; it can sort any type of data into any conceivable order! (An example using Array.sort() is in Section 7.7.3.)












No comments: