Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>NOTE: This answer was written in <strong>2008</strong>, when javascript was still in <strong>ES3</strong> from <strong>1999</strong>. A lot of new functionality has been added since then, so now better solutions exists. This answer is kept for historical reasons. </p> </blockquote> <p>The benefit of the code below is that you don't need to specify the name of the function twice and it works for anonymous functions too. </p> <pre><code>function x() { if ( (this instanceof arguments.callee) ) { alert("called as constructor"); } else { alert("called as function"); } } </code></pre> <p><strong>Update</strong> As <a href="https://stackoverflow.com/users/15055/claudiu">claudiu</a> have pointed out in a comment below, the above code doesn't work if you assign the constructor to the same object it has created. I have never written code that does that and have newer seen anyone else do that eighter. </p> <p>Claudius example:</p> <pre><code>var Z = new x(); Z.lolol = x; Z.lolol(); </code></pre> <p>By adding a property to the object, it's possible to detect if the object has been initialized. </p> <pre><code>function x() { if ( (this instanceof arguments.callee &amp;&amp; !this.hasOwnProperty("__ClaudiusCornerCase")) ) { this.__ClaudiusCornerCase=1; alert("called as constructor"); } else { alert("called as function"); } } </code></pre> <p>Even the code above will break if you delete the added property. <strong><em>You can however overwrite it with any value you like, including <code>undefined</code>, and it still works.</em></strong> But if you delete it, it will break.</p> <p>There is at this time no native support in ecmascript for detecting if a function was called as a constructor. This is the closest thing I have come up with so far, and it should work unless you delete the property.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload