I'd like to call a function without knowing how it should be called/instantiated. For my understanding there are two ways we can either use new Foo()
or Foo()
.
As I need a wrapper to call this function, let's say it's basically a proxy. I have a reference to a function but don't know in which way I should call it, wether it is meant to be a constructor or a plain javascript function.
As it seems that there is no way to distuingish between both ways I came up with the following.
var delegate;
var Foo = function() { };
Foo.prototype.foo = function() { alert("foo") };
var bar = function(value) { alert(value); }
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
var proxy = function() { return construct(delegate, arguments) };
delegate = bar;
proxy("bar");
delegate = Foo;
new proxy().foo();
This gives me the expected result and seems to work. Do you see anything bad with this solution? Is it bad to call a regular function with new
? What are the downside of this technique?
The code is based on the following question "Use of apply with the new operator"