简体   繁体   中英

What is the advantage of declaring a function using the new operator in JavaScript?

The caption says it all.

I am reading a book and in the Function chapters, the author puts forward that there are advantages of declaring a function using the new operator .

But then I have seen the declaration like

function myFunction(){
}

more often in the applications, than declaring it like,

var myFunction = new Function();

Any suggestions?

From the MDN description of Function :

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

So, from this, you see the following differences when using new Function(...) :

  1. The code for the new function is a string and is parsed when the new Function(...) is called, not when the page is parsed. For example, you can build a string and then use that as your function body.

  2. These functions are always created in the global scope and do not create closures within the environment they are created in.

  3. These functions cannot access parent scoped variables.

  4. You can dynamically construct code and then have it turned into a parsed/live function - somewhat similar to eval() , but with a few subtle differences.


Note: Because the function body with the new Function(...) construct has to be contained in a Javascript string, it's messy to write most code this way. new Function(...) should generally only be used for special circumstances where you need to construct a function body on the fly (which is likely a very rare case) and not where you know the code ahead of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM