Monday, October 15, 2007

Function() constructor of JavaScript

There are a few points that are important to understand about the Function() constructor:

The Function() constructor allows JavaScript code to be dynamically created and compiled at runtime. It is like the global eval() function (see Part III) in this way.

The Function() constructor parses the function body and creates a new function object each time it is called. If the call to the constructor appears within a loop or within a frequently called function, this process can be inefficient. By contrast, a function literal or nested function that appears within a loop or function is not recompiled each time it is encountered. Nor is a different function object created each time a function literal is encountered. (Although, as noted earlier, a new closure may be required to capture differences in the lexical scope in which the function is defined.)

A last, very important point about the Function() constructor is that the functions it creates do not use lexical scoping; instead, they are always compiled as if they were top-level functions, as the following code demonstrates:


var y = "global";
function constructFunction() {
var y = "local";
return new Function("return y"); // Does not capture the local scope!
}

// This line displays "global" because the function returned by the
// Function() constructor does not use the local scope. Had a function
// literal been used instead, this line would have displayed "local".
alert(constructFunction()()); // Displays "global"

No comments :