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
add comment

2 Answers

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
add comment

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
add comment

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.