I want to write a function like this:
function myNew(constructor) {
return constructor.applyNew(Array.prototype.slice.call(arguments, 1));
}
Only applyNew
doesn't exist. Is there a way around this?
I want to write a function like this:
function myNew(constructor) {
return constructor.applyNew(Array.prototype.slice.call(arguments, 1));
}
Only applyNew
doesn't exist. Is there a way around this?
You first have to create an object that inherits from the constructor function's prototype, and then apply the constructor function to that object to initialize it:
function applyNew(fn, args) {
var obj;
obj = Object.create(fn.prototype);
fn.apply(obj, args);
return obj;
}
Edited (I didn't think about the array before):
function myNew(constructor) {
var args = arguments;
function F() {
return constructor.apply(this, Array.prototype.slice.call(args, 1));
}
F.prototype = constructor.prototype;
return new F();
}