I use the following function to create instances of functions in JavaScript from an array of arguments:
var instantiate = function (instantiate) {
return function (constructor, args, prototype) {
"use strict";
if (prototype) {
var proto = constructor.prototype;
constructor.prototype = prototype;
}
var instance = instantiate(constructor, args);
if (proto) constructor.prototype = proto;
return instance;
};
}(Function.prototype.apply.bind(function () {
var args = Array.prototype.slice.call(arguments);
var constructor = Function.prototype.bind.apply(this, [null].concat(args));
return new constructor;
}));
Using the above function you can create instances as follows (see the fiddle):
var f = instantiate(F, [], G.prototype);
alert(f instanceof F); // false
alert(f instanceof G); // true
f.alert(); // F
function F() {
this.alert = function () {
alert("F");
};
}
function G() {
this.alert = function () {
alert("G");
};
}
The above code works for user built constructors like F
. However it doesn't work for native constructors like Array
for obvious security reasons. You may always create an array and then change its __proto__
property but I am using this code in Rhino so it won't work there. Is there any other way to achieve the same result in JavaScript?