4

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.

theonlygusti
  • 7,942
  • 8
  • 40
  • 80
  • 2
    The anonymous function in your code returns a [new instance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function) of `doStuff`. – Teemu Mar 04 '14 at 17:25
  • Same as return new Array(); but this time it is a function object – Kalzem Mar 04 '14 at 17:26
  • @BabyAzerty — Since the internals of `Array()` aren't really visible (And since Array does a bunch of stuff to make it not matter if you use `new` or not) that isn't very helpful. – Quentin Mar 04 '14 at 17:29
  • @Quentin : Mozilla dev does the difference between an Array object and a Function object [link ref](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects) . Besides, it is easier for most developpers (coming from other languages) to understand an Array object better than a Function object – Kalzem Mar 04 '14 at 17:38

1 Answers1

5

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

ppoliani
  • 4,266
  • 2
  • 30
  • 58