次の関数を使用して、引数の配列からJavaScriptで関数のインスタンスを作成します。
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;
}));
上記の関数を使用すると、次のようにインスタンスを作成できます(フィドルを参照)。
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");
};
}
上記のコードは、のようなユーザー作成のコンストラクターで機能しますF
。Array
ただし、明らかなセキュリティ上の理由から、ネイティブコンストラクタでは機能しません。いつでも配列を作成してからその__proto__
プロパティを変更できますが、私はRhinoでこのコードを使用しているため、そこでは機能しません。JavaScriptで同じ結果を達成する他の方法はありますか?