JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

8.7.6 The Function() Constructor

8.7.6 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 strings 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:

var scope = "global";

function constructFunction() {

var scope = "local";

return new Function("return scope"); // Does not capture the local scope!

}

// This line returns "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() (see §4.12.2 ) that defines new variables and functions in its own private scope. You should rarely need to use this constructor in your code.

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31370.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1