SomeConstructorFunction
である。これにより、既存のインスタンスとSomeConstructorFunction
の間のリンクがクリアされます。最終的なものはSomeConstructorFunction
の有効なインスタンスになります。
function SomeConstructorFunction() {
}
function extendAndInstantiate(constructorFn) {
constructorFn.prototype = {}; //New instance as prototype
return new constructorFn();
}
var child1 = extendAndInstantiate(SomeConstructorFunction);
console.log(child1 instanceof SomeConstructorFunction); //true
var child2 = extendAndInstantiate(SomeConstructorFunction);
console.log(child1 instanceof SomeConstructorFunction); //false
console.log(child2 instanceof SomeConstructorFunction); //true
var child3 = extendAndInstantiate(SomeConstructorFunction);
console.log(child1 instanceof SomeConstructorFunction); //false
console.log(child2 instanceof SomeConstructorFunction); //false
console.log(child3 instanceof SomeConstructorFunction); //true
だからどちらかあなたは方法は、@ ben336で示した従うか、以下に示すようにプロトタイプを割り当てる前に、条件のチェックを行うことができます。
function Base(){
}
function SomeConstructorFunction() {
}
function extendAndInstantiate(constructorFn, Base) {
if(!(constructorFn.prototype instanceof Base)){
console.log(" extend only once ");
constructorFn.prototype = new Base();
}
return new constructorFn();
}
var child1 = extendAndInstantiate(SomeConstructorFunction, Base);
console.log(child1 instanceof SomeConstructorFunction); //true
var child2 = extendAndInstantiate(SomeConstructorFunction, Base);
console.log(child1 instanceof SomeConstructorFunction); //true
console.log(child2 instanceof SomeConstructorFunction); //true
var child3 = extendAndInstantiate(SomeConstructorFunction, Base);
console.log(child1 instanceof SomeConstructorFunction); //true
console.log(child2 instanceof SomeConstructorFunction); //true
console.log(child3 instanceof SomeConstructorFunction); //true
プロトタイプ継承の大きな説明。私はOPの混乱は 'constructorFn.prototype = {};にあると思う。 //任意のプロトタイプにすることができます。彼はプロトタイプを同じ** value **に設定すると 'instanceof'が真となることを期待しています。代わりに同じ**リファレンス**に設定する必要があります。 – MattDiamant
@MattDiamant - 私は同意します。私はOPが 'extendAndInstantiate'を使って何を達成しようとしているのか分かりませんが、私は以下の質問で私自身の' instantiate'関数のように思っています:http://stackoverflow.com/q/11490606/783743 –
。最も重要なのは、プロトタイプを '{}'に設定すると、 'SomeConstructorFunction'の型が' Object'に効果的に変更されたという事実がありませんでした。 'SomeConstructorFunction.constructor'は' function Object ... 'です。 – Stephen