Is there a way for a JavaScript function to know whether it was called normally or in conjunction with "new"?
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/367768/how-to-detect-if-a-function-is-called-as-constructor">How to detect if a function is called as constructor?</a>  </p>
</blockquote>



<p>I would like to have a function in JavaScript which behaves differently if it's called normally or if it's invoked in order to create a new instance. There could be many different uses, where the two functionalities can be related or not related. One use would be to exempt the coder from having to type <code>new</code>, when the function is always used to create new instances:</p>

<pre><code>function MyClass(arg1, arg2) {
  if(/* not called with "new" */) return new MyClass(arg1, arg2);

  // instance initialization stuff here...

}
</code></pre>

<p>This way I wouldn't have to type <code>var x = new MyClass(arg1, arg2)</code>: it would be enough to type <code>var x = MyClass(arg1, arg2)</code> (but the former wouldn't be wrong either).</p>

<p>Just one example of a possible use.</p>

<p>Can this be done? If so, how?</p>
