public メソッドを持たない js クラスがあります。コンストラクター内で var を使用してこれらのメソッドを作成し、methodName() で呼び出しています。代わりに class.prototype.methodName を使用し、クラス内で this.methodName() を使用して呼び出す必要がありますか? どちらのアプローチの利点は何ですか? プロトタイプ メソッドが新しいインスタンスにコピーされるため、高速になることはわかっています。しかし、それらはクラスの API にのみ使用する必要がありますか?
1 に答える
JavaScript にはプライベート変数がないため、それらをシミュレートするパターンを使用するとオーバーヘッドが発生します (コードを実行するには、より多くの CPU とメモリが必要です)。プライベートを含むコードは、保守が難しくなる可能性があります。
プライベート メンバーをシミュレートするパターンは、次の 2 つの異なるタイプに分けることができます。
- インスタンス固有のメンバー
- プロトタイプメンバー
インスタンス固有は人の宗教のようなものであり、プロトタイプ メンバーは doSomethingDangerous 関数である可能性があります。宗教が値を返す前に、要求元のオブジェクトがこの個人情報にアクセスできるかどうかを確認する必要がある場合があります。関数 doSomethingDangerous を直接呼び出すべきではありません。これは、Person の外部から呼び出された場合、それを実行する前に適切な予防措置が取られているかどうか確信が持てないためです。
「プライベート」メンバーにアクセスできるメソッドは特権メソッドです。インスタンス固有のメンバーにアクセスする必要がある場合は、コンストラクター本体 (インスタンス固有のメンバーが宣言されている場所) にある必要があります。プロトタイプ固有のメンバーにアクセスする必要がある場合は、「プライベート」が宣言されている場所と同じボディにある必要があります。
次に例を示します。
//constructor for Person
var Person = function(){//<=start body of constructor function
//to properly use prototype and not cause your code to consume
// more resources to simulate something that isn't supported
// in JavaScript "private" variable names usually start with _
// so other programmers know not to set, get or call this directly
this._normalPrivate;
var religion = undefined;//<=instance specific private
this.religion = function(){//<=privileged function
console.log(religion);//<=can access private instance here
}
};
Person.prototype=(function(){//<=start body of function returning object for prototype
//All person instances share this, it's not instance specific
var doSomethingDangerous=function(){//<=private prototype
// doing something dangerous, don't want this to be called directly
};
return {
doSomething:function(){//<=priviliged method, can access private prototype
//we cannot access religion because it's defined in a different
// function body
//make sure we can do something dangerous
doSomethingDangerous();
}
};
}());
Person.prototype.constructor=Person;
Person.prototype.anotherMethod=function(){
//not a privileged method, cannot access doSomethingDangerous or religion
};
var ben = new Person();
ただし、private は他のプログラマーにこれらのメンバーに直接アクセスしないことを示すためにのみ使用されるため、私はこのパターンを使用しません。次の例のように、プログラマー (将来の自分自身を含む) に次のようなことをさせたくない:
ben._doSomethingDangerous();
doSomethingDangerous が非公開であることを他のプログラマ (および将来の自分) に示すには、その前にアンダースコアを追加します。
Person.prototype._doSomethingDangerous=function(){...
プロトタイプ、継承、ミックスインの詳細はこちらhttps://stackoverflow.com/a/16063711/1641941