I'm trying to figure out how to call a constructor function with an arbitrary number of arguments (passing the arguments on from some other function call).
I have a set of base and derived objects in javascript. One of the methods on the base object is called makeNew()
and its job is create a new object of the same type as whatever object it's called on and process all the same arguments as the normal constructor would on the new object. The point of this makeNew()
method is that there are other methods that want to create a new object of the same type as the current object, but they won't know what type that is because it may be a type that inherits from the base class. Note, I don't want a whole clone of the current object, but rather a new object of the same type, but initialized with different initial arguments to the constructor.
The simple version of makeNew()
is this:
set.prototype.makeNew = function() {
return new this.constructor();
}
This works for creating an empty object of the same type as the current one because if it's an inherited object type, then this.constructor
will be the inherited constructor and it will make the right type of object.
But, when I want to pass on arbitrary arguments to the constructor so normal constructor arguments can be passed to makeNew()
, I can't figure out how to do it. I tried this:
set.prototype.makeNew = function() {
return new this.constructor.apply(this, arguments);
}
But, that code gives me this error in Chrome:
Error: function apply() { [native code] } is not a constructor
Any idea how to pass on arbitrary arguments to a constructor function?