¿Cómo podría generalizar la siguiente función para tomar N argumentos? (¿Usar llamadas o postularse?)¿Cómo puedo llamar a un constructor de Javascript usando call o apply?
¿Existe alguna manera programática de aplicar argumentos a 'nuevo'? No quiero que el constructor sea tratado como una función simple.
/**
* This higher level function takes a constructor and arguments
* and returns a function, which when called will return the
* lazily constructed value.
*
* All the arguments, except the first are pased to the constructor.
*
* @param {Function} constructor
*/
function conthunktor(Constructor) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
console.log(args);
if (args.length === 0) {
return new Constructor();
}
if (args.length === 1) {
return new Constructor(args[0]);
}
if (args.length === 2) {
return new Constructor(args[0], args[1]);
}
if (args.length === 3) {
return new Constructor(args[0], args[1], args[2]);
}
throw("too many arguments");
}
}
prueba qUnit:
test("conthunktorTest", function() {
function MyConstructor(arg0, arg1) {
this.arg0 = arg0;
this.arg1 = arg1;
}
MyConstructor.prototype.toString = function() {
return this.arg0 + " " + this.arg1;
}
var thunk = conthunktor(MyConstructor, "hello", "world");
var my_object = thunk();
deepEqual(my_object.toString(), "hello world");
});
Ben Nadel [escribió sobre esto] (http: //www.bennadel. com/blog/2291-Invocando-A-Native-JavaScript-Constructor-Using-Call-Or-Apply-.htm) ampliamente. –