Use of .apply() with 'new' operator. Is this possible?

Posted by Premasagar on Stack Overflow See other posts from Stack Overflow or by Premasagar
Published on 2009-10-22T12:15:09Z Indexed on 2014/06/12 3:26 UTC
Read the original article Hit count: 61

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

What I want to do is something like this (but the code below does not work):

function Something(){
    // init stuff
}
function createSomething(){
    return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something

The Answer

From the responses here, it became clear that there's no in-built way to call .apply() with the new operator. However, people suggested a number of really interesting solutions to the problem.

My preferred solution was this one from Matthew Crumley (I've modified it to pass the arguments property):

var createSomething = (function() {
    function F(args) {
        return Something.apply(this, args);
    }
    F.prototype = Something.prototype;

    return function() {
        return new F(arguments);
    }
})();

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about oop