Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In what all aspects, calling a function with and without new keyword differ in javascript? I mean what all things are differing between?

testFn() vs new testFn()

share|improve this question

2 Answers 2

up vote 6 down vote accepted

new creates a new (empty) object and sets this to it, then calls the function, which acts as the constructor for the object (by manipulating this.something). Calling the same function without the new keyword would let it act on whatever this currently means.

share|improve this answer
    
Is there anything more to this? –  akp Jan 16 '13 at 18:12
    
@akp no it's really that simple. Except what was not mentioned is that if the function explicitly returns a reference type, that is returned by new and the created object is wasted. –  Esailija Mar 25 '13 at 1:04
1  
Using new will cause the new object's prototype to be set to reference that of the first function to which the new object is passed. I don't think that behavior can be legitimately achieved via other means. –  supercat Jul 26 at 0:28
    
You are right, I missed that. –  user281377 Jul 29 at 10:45

These variants are syntactically different: with "new" variant supposes that the function is a constructor. The variant without "new" supposes, that it is not a constructor.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.