Get the App
SLTechnology News&Howtos  ›  Development  › 

How JavaScript uses the Function () constructor

Shulou Source: shulou.com Published: 2022-06-01 03:09:03 10月16日 Update

This article mainly introduces how JavaScript uses the Function () constructor. It is very detailed and has a certain reference value. Friends who are interested must read it!

Function () constructor

Look at the code first:

Var f = new Function ("x", "y", "return xroomy"); / / Function () constructor var f = function (xmemy) {return xonomy}; / / the two codes are equivalent

Through this method, we can pass in any number of string arguments, and the text represented by the last argument is the function body, this method can contain any number of JavaScript statements, and if the constructed function does not contain any parameters, we only need to enter a function. This method is different from the other two methods. This method allows JavaScript to create translation functions dynamically at run time, and the function parses the function body every time we call this method. Therefore, if it is used repeatedly or recycled, the efficiency will be affected. In contrast, nested functions and function definition expressions in the loop are not recompiled every time they are executed.

Another thing to note about this constructor is that the function it creates does not use lexical scope, all because the function body code is always executed at the top level when compiled, as shown below:

Var a = 3; / declare the variable afunction f () {var a = 2 in the top-level function; / / declare the local variable areturn new Function ("return aura;") in the function body; / / cannot capture the local scope} console.log (f () ()); / / the console outputs 9 instead of 4, indicating that the compilation of the constructor is executed in the top-level function.

So we can execute eval () in the global scope for this problem.

That's all of the article "how JavaScript uses the Function () constructor". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Function method time code function top-level compilation content variable local quantity article loop two value global interest dynamic parameter character Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Docker NVidia MySQL