Assigning a function to a variable with the Function constructor. Suppose you create the variable multiply using the Function constructor, as shown in the preceding section:
var multiply = new Function("x", "y", "return x * y")
This is similar to declaring the following function:
function multiply(x,y) { return x*y }
Assigning a function to a variable using the Function constructor is similar to declaring a function with the function statement, but they have differences:
Nesting functions. You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:
The following example shows nested functions: function addSquares (a,b) { function square(x) { return x*x } return square(a) + square(b) } a=addSquares(2,3) // returns 13 b=addSquares(3,4) // returns 25 c=addSquares(4,5) // returns 41 When a function contains a nested function, you can call the outer function and specify arguments for both the outer and inner function: function outside(x) { function inside(y) { return x+y } return inside } result=outside(3)(5) // returns 8
Specifying an event handler with a Function object.
The following code assigns a function to a window's onFocus event handler (the event handler must be spelled in all lowercase):
window.onfocus = new Function("document.bgColor='antiquewhite'")
If a function is assigned to a variable, you can assign the variable to an event handler. The following code assigns a function to the variable setBGColor.
var setBGColor = new Function("document.bgColor='antiquewhite'")
You can use this variable to assign a function to an event handler in either of the following ways:
document.form1.colorButton.onclick=setBGColor <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color" onClick="setBGColor()">
Once you have a reference to a Function object, you can use it like a function and it will convert from an object to a function:
Event handlers do not take arguments, so you cannot declare any arguments in a Function constructor for an event handler. For example, you cannot call the function multiply by setting a button's onclick property as follows:
document.form1.button1.onclick=multFun(5,10)
frames[0].onfocus = new Function("document.bgColor='antiquewhite'")
解释:把一个Function给了一个事件,而这个Function定义时没有参数,只有方法体,这种情况是允许的,属于没有参数,只有方法体的方法。