技術的には可能ですが、問題をよりエレガントに解決できます (説明は以下に続きます)。
function mything() {
var a, b, c;
function PrivateConstructor() {
this.publicFunc = function() {}
}
// this is the magic that makes it happen:
PrivateConstructor.prototype = mything.prototype;
return new PrivateConstructor();
}
mything1 = mything();
assert(mything1 instanceof mything); // passes
または、EcmaScript 5 機能を使用すると、次のようになります。
function mything() {
var a, b, c;
var object = Object.create(mything.prototype);
object.publicFunc = function() {}
return object;
}
mything1 = mything();
assert(mything1 instanceof mything); // passes
説明
instanceof
右側のオペランドが関数であり、その関数のプロパティに格納されているオブジェクトが左側のオペランドのプロトタイプ チェーンに含まれている場合、演算子は true を返しprototype
ます。
最初の例は、1 つのオブジェクト (プロトタイプ チェーン内)mything.prototype
を生成するためにのみ使用される別の一時的な関数の "prototype" プロパティとして再利用します。2 番目の例では、 を使用して から直接mything.prototype
継承することにより、そのようなオブジェクトを作成します。mything.prototype
Object.create()
どちらのオブジェクトも から継承mything.prototype
するため、object instanceof mything
テストに合格します。
そうは言っても、jfriend00 によって提案されたパターンはオーバーヘッドが少なく、必要な機能を提供しながら読みやすくなっています。