Function to spawn arbitrary object with arbitrary argument list in Javascript

Good news, everyone!

This function can be used to create an instance of an arbitrary class, and pass the list of arguments to the class’s constructor.

var spawn = function(cls, args) {
  if(!args instanceof Array) args = [args];
  var f=function(){};
  f.prototype.constructor = cls;
  var obj = new f();
  return obj;


var myClass = function(a,b,c){ this.a=a; this.b=b; this.c=c; }
var myInstance = spawn(myClass,[1,2,3]); // same as myInstance = new myClass(1,2,3);

So, you may ask, why not just use the new keyword? Because new can’t be used to pass an unknown length of arguments to the constructor, that’s why! Another way to say that is:

spawn : new :: apply() : call()

So, if your class and your argument list are being set at run-time, this function allows you to create objects without relying on knowing the number of arguments to pass to the constructor, like so:

var Collection = function(cls) {
    this.class = cls;
    this.stack = [];
  make:function() {
    var thing = spawn(this.class,arguments);
    return thing;
var myClassCollection = new Collection(myClass);
alert(myClassCollection.stack[0].a); // “123″


Leave a Reply

Comments are moderated like crazy using a variety of plugins. There is a very high likelihood that your comment won't show up right away, especially if you have never commented here before, but it was not deleted.

Please be patient, and do not post your comment more than once. It will show up once it is approved.

You must be logged in to post a comment.