JavaScript factory with optional arguments

The problem is that I need to create a new instance of the passed class

Is there a way to rewrite this function so that it can accept any number of arguments?

function createInstance(ofClass, arg1, arg2, arg3, ..., argN){ return new ofClass(arg1, arg2, arg3, ..., argN); } 

This function should create an instance of a past class. Example:

 var SomeClass = function(arg1, arg2, arg3){ this.someAttr = arg3; ..... } SomeClass.prototype.method = function(){} var instance = createInstance(SomeClass, 'arg1', 'arg2', 'arg3'); 

So that must be true.

 instance instanceof SomeClass == true 

Right now, I have limited N to 25, hoping that more arguments are rarely used.

+4
source share
2 answers

Other answers are on the right track, but none of them mention that you need to know that arguments not Array . This is a special structure that behaves like an Array .

So, before using it as an Array , you can convert it to one of the following:

 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); } 

Sorry, I just copied the code with constructor , etc. and didn’t think about what he would actually do. I updated it now to what you want. You will find that it invokes the constructor without new , so you will not get the same behavior. However, John Resig (author of jQuery) wrote on this very topic .

So, based on an article by John Resig, you have two ways to solve this problem. A more complex solution will be the most transparent to the user, but it depends on which solution you choose.


Here is the “perfect” solution if you only intend to support browsers that have the Object.create function (now this is a fairly large percentage compared to three years earlier):

 function createInstance(cls) { var obj = Object.create(cls.prototype); var args = Array.prototype.slice.call(arguments, 1); cls.apply(obj, args); return obj; } 

The resulting objects from new cls(x) and createInstance(cls, x) must be identical.

+10
source

There is always an array

+4
source

All Articles