7

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)") 
7
  • 1
    No difference in this case. Commented Apr 5, 2016 at 3:11
  • So, disregarding this case, in what case there would be a difference? Commented Apr 5, 2016 at 3:11
  • 2
    There is no difference with Function. It's defined to behave the same either way. "When Function is called as a function rather than as a constructor, it creates and initializes a new Function object." Commented Apr 5, 2016 at 3:12
  • String and Number pretty much, ... Boolean Commented Apr 5, 2016 at 3:12
  • 2
    It is a technique used in some constructors where if it is invoked without new(ie this is the global object, then it self invokes as a constructor) Commented Apr 5, 2016 at 3:12

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How does something so fundamental not have a squillion upvotes.
1

The difference is that when you invoke the function with a new keyword it creates a new 'this' empty object for your function and you can set properties on that inside your function. Also the return value from your new-ly called function will be this if you do not return something else.

With no new keyword there's no new empty 'this' object so if you are using that inside it will error out.

You might not be using this at all in your function so you may see no differences at all.

p.s.: One problem might be that if you are using this and you invoke without the new kw. the this will be the global this inside the fn. - and in a browser environment that will be the window object... so you will be setting props on that instead of on a plain new empty obj.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.