theonlygusti theonlygusti - 1 year ago 81
Javascript Question

What is return new function(); in JavaScript?

In js code I have seen this used:

function doStuff( selector ) {
/* Stuff to do with selector */

var q = function( selector ) {
return new doStuff( selector );

What exactly is happening? What is
return new
really doing? It seems to pass its arguments to the other function, but would someone please be kind enough to walk me through the process?

All and any help is appreciated, thanks in advance.

Answer Source

When we call a function with the new keyword. the following will happen:

  • A new object will be created in the memory
  • The scope of that object will be passed to the function; So the this keyword will refer to that object.
  • The newly created object will be returned.

So in essence, that is how you create instances in JavaScript. You need to call a function with the new keyword. When doing so, the function is called constructor.

In your example, the q function returns an instance of the doStuff method. Bare in mind though that the naming convention is not correct.

Constructors should be nouns rather that verbs and they should be in Pascal-case, not camel-case