The function object in js is a fascinating thing, but it is often confusing because it is too flexible.
Let me show you a 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 is your first feeling when you see these two? All return "local"? ? If this is the case, you need to take a closer look at the explanation below. constructFunction2() should be easy to understand the closure, and I won't go into details here. Next, I will focus on the situation of constructFunction().
The Function() constructor is used here. Although the Function() constructor is not very commonly used, it is still necessary to understand it.
Whether it is a function definition statement or a function direct quantitative expression, the function definition must use the function() keyword. Single functions can also be defined by 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, and the text represented by the last argument is the function body; it can contain any Javascript statement, and each statement is divided by a semicolon. All other argument strings passed into the constructor are strings that specify the name of the function. If the defined function does not contain any parameters, simply pass a string function body to the constructor.
There are several points to pay special attention to about the Function() constructor:
1. Function() constructor allows JavaScript to dynamically create and compile functions at runtime.
2. Every time the Function() constructor is called, the function body will be parsed and a new function object will be created. If this constructor is executed in a loop or multiple calls, the execution efficiency will be affected. In contrast, nested functions and function definition expressions in loops are not recompiled every time they are executed.
2. The last point is also a very important point about the Function() constructor, that is, the functions it creates do not use lexical scope. On the contrary, the compilation of function body code will always be executed at the top-level function. After reading this, the above function constructFunction()(); it should be easy to understand to return "global"?
The above is the JS Function() constructor introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!