The JavaScript Function ObjectBelieve it or not, JavaScript can treat functions as data typeswith the result that you can declare a function as a variable. You can do this with the JavaScript Function object. Here's an example showing how this works. In this case, I'll create a function named adder that will take two operands, which I'll name operand1 and operand2 , add them, and return their sum. You can do that with a new Function object as follows . (Recall that you have to use the new keyword when creating a new object.) var adder = new Function("operand1", "operand2", "return operand1 + operand2") Here, I pass the name of the first operand, then the second operand, and then the JavaScript code for the function. (You can specify as many function parameters as you wantup to 255 in JavaScriptnot just the two I've used here.) Now you can use this new function as you would any other: var adder = new Function("operand1", "operand2", "return operand1 + operand2") document.write("2 + 3 = " + adder(2, 3)) The Function object has been available since Netscape Navigator version 3.0 and Internet Explorer version 3b, as you see in Table 3.11. (Earlier, unreliable versions of this object were available in Netscape Navigator version 2.0 and Internet Explorer version 3a.) You can find the properties of this object in Table 3.12 and the methods of this object in Table 3.13. (It has no events.) Table 3.11. The Function Object
Table 3.12. Properties of the Function Object
Table 3.13. Methods of the Function Object
|