Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I construct a JavaScript object without using the new keyword?
    text
    copied!<p>Here is what I'd like to do:</p> <pre><code>function a() { // ... } function b() { // Some magic, return a new object. } var c = b(); c instanceof b // -&gt; true c instanceof a // -&gt; true b instanceof a // -&gt; true </code></pre> <p>Is it possible? I can make <code>b</code> be an instance of <code>a</code> easily by hooking <code>a</code> into its prototype chain but then I have to do <code>new b()</code>, which is what I'm trying to avoid. Is what I want possible?</p> <p><strong>Update:</strong> I feel that it might be possible with judicious use of <code>b.__proto__ = a.prototype</code>. I'm going to experiment more after work.</p> <p><strong>Update 2:</strong> Below is what seems to be the closest you can get, which is good enough for me. Thanks all for the interesting answers.</p> <pre><code>function a() { // ... } function b() { if (!(this instanceof arguments.callee)) { return new arguments.callee(); } } b.__proto__ = a.prototype var c = b(); c instanceof b // -&gt; true c instanceof a // -&gt; false b instanceof a // -&gt; true </code></pre> <p><strong>Update 3:</strong> I found exactly what I wanted in a <a href="http://blog.higher-order.net/2008/02/21/javascript-parasitic-inheritance-power-constructors-and-instanceof/" rel="noreferrer">blog post on 'power constructors'</a>, once I added the essential <code>b.__proto__ = a.prototype</code> line:</p> <pre><code>var object = (function() { function F() {} return function(o) { F.prototype = o; return new F(); }; })(); function a(proto) { var p = object(proto || a.prototype); return p; } function b(proto) { var g = object(a(proto || b.prototype)); return g; } b.prototype = object(a.prototype); b.__proto__ = a.prototype; var c = b(); c instanceof b // -&gt; true c instanceof a // -&gt; true b instanceof a // -&gt; true a() instanceof a // -&gt; true </code></pre>
 

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