Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no reliable way to distinguish how a function is called in JavaScript code.<sup>1</sup></p> <p>However, a function call will have <code>this</code> assigned to the global object, while a constructor will have <code>this</code> assigned to a new object. This new object cannot ever be the global object, because even if an implementation allows you to set the global object, you still haven't had the chance to do it.</p> <p>You can get the global object by having a function called as a function (heh) returning <code>this</code>.</p> <p>My intuition is that in the specification of ECMAScript 1.3, constructors that have a defined behavior for when called as a function are supposed to distinguish how they were called using this comparison:</p> <pre><code>function MyClass () { if ( this === (function () { return this; })() ) { // called as a function } else { // called as a constructor } } </code></pre> <p>Anyway, anyone can just use a function's or constructor's <code>call</code> or <code>apply</code> and set <code>this</code> to anything. But this way, you can avoid "initializing" the global object:</p> <pre><code>function MyClass () { if ( this === (function () { return this; })() ) { // Maybe the caller forgot the "new" keyword return new MyClass(); } else { // initialize } } </code></pre> <hr> <p><sub>1. </sub>The host (aka implementation) may be able to tell the difference, if it implements the equivalent to the internal properties <code>[[Call]]</code> and <code>[[Construct]]</code>. The former is invoked for function or method expressions, while the latter is invoked for <code>new</code> expressions.</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.
    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