The Function() Constructor
Posted tsai-87
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了The Function() Constructor相关的知识,希望对你有一定的参考价值。
Functions are usually defined using the function keyword, either in the form of a function definition statement or a function literal expression. But functions can also be defined with the Function() constructor. For example:
var f = new Function("x", "y", "return x*y;");
This line of code creates a new function that is more or less equivalent to a function defined with the familiar syntax:
var f = function(x,y) { return x*y; }
The Function() constructor expects any number of string arguments. The last argument is the text of the function body; it can contain arbitrary javascript statements, separated from each other by semicolons. All other arguments to the constructor are string that specify the parameters names for the function. If you are defining a function that takes no arguments, you simply pass a single string -- the function body -- to the constructor.
Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. Like function literals, the Function() constructor creates anonymous functions.
There are a few points that are important to understand about the Function() constructor:
The Function() construnctor allows JavaScript functions to be dynamically created and compiled at runtime.
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, nested function and function definition expressions that appear within loops are not recompiled each time they are encountered.
At last, very important point about Function() constructor is that the functions it creates do not use the lexical scoping; instead, they are always compiled as if they were top-level functions, as the following code demonstrates:
var scope = "global";
function constructFunction() {
var scope = "local";
return new Function("return scope"); //Does not capture the local scope
}
// This line return "global" because the function returned by the
// Function() constructor does not use the local scope.
constructFunction()(); // => "global"
The Function() constructor is best thought of as a globally-scoped version of eval() that defines new variables and functions in its own private scope. You should rarely need to use this constructor in your code.
以上是关于The Function() Constructor的主要内容,如果未能解决你的问题,请参考以下文章
Closure as the function parameter
hdu-2824 The Euler function(欧拉函数)
[Cycle,js] Customizing effects from the main function