title: Advanced Javascript: Detecting whether current function is being called by a constructor
body: <p>Within a Javascript function it is a rather simple detection whether the function has been simply executed or being executed as an object instance constructor (using <code>new</code> keyword).</p>
  <pre><code>// constructor
  function SomeType() {
      if (this instanceof SomeType)
          // called as an object instance constructor
      else
          // the usual function call
  }
  </code></pre>
  <p>That's fine, this has been answered here at SO at least a few times before.</p>
  <p>So let's suppose now that our constructor function calls another function that I defined directly on Function prototype and is therefore accessible to all functions - the main purpose why I'm doing it this way.</p>
  <pre><code>Function.prototype.doSomething = function doSomething() {
      // what code here?
  };
  
  // constructor
  function SomeType() {
      SomeType.doSomething();
  }
  </code></pre>
  <h2>Main problem</h2>
  <p>How can we now detect within <code>doSomething</code> the same for <code>SomeType</code> function?</p>
  <p>The reason why I'd like to detect it is I'm writing a function that <em>adopts</em>/<em>injects</em> constructor parameters as constructed object instance members with the same name. Of course this function should only execute when it's being called by a constructor function and not by a function called regularly.</p>
  <p><a href="https://stackoverflow.com/a/27838697/75642">This is my answer</a> to another question where you can see my <code>adoptArguments</code> function that puts object constructor arguments into constructed object instance as members.</p>
  <h3>Workaround that enforces specific usage = bad</h3>
  <p>I have a possible workaround that I don't want to use, because it enforces correct usage - execution context injection. This is the code that can detect object instance constructor execution:</p>
  <pre><code>Function.prototype.doSomething = function doSomething() {
      if (this instanceof doSomething.caller)
      {
          // object instance construction
      }
      else return; // nope, just normal function call
  };
  
  // constructor
  function SomeType() {
      // required use of &quot;.call&quot; or &quot;.apply&quot;
      SomeType.doSomething.call(this);
  }
  </code></pre>
  <p>This idea may spark some ideas of your own to solve the original problem</p>