Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between new Function and Function

Tags:

javascript

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)")
like image 455
GBarroso Avatar asked Jul 31 '26 23:07

GBarroso


1 Answers

From the docs:

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

...

Invoking the Function constructor 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().

tl;dr

There is no difference.

like image 147
Akshat Mahajan Avatar answered Aug 03 '26 12:08

Akshat Mahajan