It's quite common to see codes using new Function, instead of simply Function. I want to understand why, what exactly the new operator is doing here.
What's the difference between these two?
var y = new Function("a", "alert(a)")
var x = Function("a", "alert(a)")
From the docs:
The
Functionconstructor creates a newFunctionobject. In JavaScript every function is actually aFunctionobject....
Invoking the
Functionconstructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
Since functions are actually objects in Javascript, it is possible to call them both via standard invocation syntax and the new operator (which instantiates a new object of type Function in this case).
What that last line I quoted from the docs is saying is that doing Function() is identical to calling new Function().
There is no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With