Short question, if this works (and it does):
eval("new " + generator.className + "(" + generator.constructorArgs.join(", ") + ")");
why doesn’t this work:
eval(generator.className + ".prototype.constructor.apply({}, generator.constructorArgs);");
The second expression always returns undefined, but in my opinion it should work. I tried it on dummy objects like:
var dummy = function () {};
Also, is there any way I can avoid using eval in this situation?
Thanks,
Alex
Well, I think the problem is that your constructor function is not returning anything.
When you use the
newoperator, if the constructor function, does not return an object, thethisvalue, which is the newly created object is returned implicitly, for example:If you invoke the function with call/apply, it will yield
undefined, since there is no return value at all:So, the solution would be to return the
thisvalue on your constructor, e.g.:Also, remember that using the
newoperator is not completely equivalent to apply a function using a new object as thethisvalue, because when you use thenewoperator, the newly created object will inherit from its constructor’s prototype, e.g.: