Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The other answers are on the right track, but none of them mention that you have to be aware of the fact that <code>arguments</code> is <em>not</em> an <code>Array</code>. It's a special structure that behaves like an <code>Array</code>.</p> <p>So before you use it like an <code>Array</code>, you can convert it to one like this:</p> <pre><code>function createInstance(cls) { // This will use the slice function of the Array type, effectively converting // the arguments structure to an Array and throwing away the first argument, // which is cls. var args = Array.prototype.slice.call(arguments, 1); return cls.apply(this, args); } </code></pre> <p>Sorry, I just copied the code with <code>constructor</code> etc. and didn't think about what it would actually do. I've updated it now to what you want. You'll find that it's calling the constructor <em>without</em> <code>new</code>, so you won't get the same behavior. However, John Resig (author of jQuery) <a href="http://ejohn.org/blog/simple-class-instantiation/" rel="nofollow noreferrer">wrote on this very issue</a>.</p> <p>So based on John Resig's article you've got two ways to solve it. The more elaborate solution will be the most transparent to the user, but it's up to you which solution you choose.</p> <hr> <p>Here is a "perfect" solution if you only intend to support browsers that have the <code>Object.create</code> function (which is a pretty big percentage now compared to three years ago):</p> <pre><code>function createInstance(cls) { var obj = Object.create(cls.prototype); var args = Array.prototype.slice.call(arguments, 1); cls.apply(obj, args); return obj; } </code></pre> <p>The resulting objects from both <code>new cls(x)</code> and <code>createInstance(cls, x)</code> should be identical.</p>
 

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