The function object in JS is a fascinating thing, but because he is too flexible, it is often confusing.
Let's take a look at the code snippet first.
var scope= "global";
function Constructfunction () {
var scope= "local";
return new Function (' return scope ');
}
Constructfunction () ();
function ConstructFunction2 () {
var scope= "local";
return function () {return
scope;
}
}
ConstructFunction2 () ();
What's your first impression of seeing these two? All return to "local"?? , if this is the case, you need to take a good look at the following explanation. ConstructFunction2 () Understand the closure should be easy to know the answer is "local", here is not detailed. Let me highlight the Constructfunction ().
function () constructor is used here, function () constructor is not very common, but it is necessary to understand.
Whether it is through a function definition statement or a function direct quantity expression, the function definition uses the function () keyword. A single function can also be defined by a function () constructor, such as:
var f=new Function ("x", "Y", "return X*y");
The actual effect of this line is equivalent to the following line of code.
var f=function (x,y) {x*y};
The function () constructor can pass in any number of string arguments, the text represented by the last argument is a body of functions, it can contain any JavaScript statements, and each statement is separated by a semicolon. All other argument strings that pass in the constructor are strings that specify the name of the function. If the defined function does not contain any arguments, simply pass the constructor to a string function body.
About the function () constructor you need to pay special attention to a few things:
The 1.Function () constructor allows JavaScript to dynamically create and compile functions at run time.
2. Every time the function () constructor is invoked, it resolves the body and creates a new function object. Execution efficiency can be affected if the constructor is executed in a loop or a function that is called more than once. In contrast, nested functions and function definition expressions in loops are not recompiled every time they are executed.
2. The final point, as well as about the function () constructor, is that the functions it creates do not use lexical scopes, and instead, the compilation of the function body code is always performed at the top-level function. After reading this, the above function constructfunction (), and returning "global" should be easy to understand?
The above is a small series to introduce the JS function () constructor, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!