Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  15] [ 7]  / answers: 1 / hits: 13412  / 10 Years ago, tue, march 4, 2014, 12:00:00

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.


More From » function

 Answers
2

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


[#47174] Monday, March 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
santiago

Total Points: 375
Total Questions: 106
Total Answers: 97

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;