最近の質問から、Java のように考えていることがわかりますが、Java はそうではありません。
最初の質問:
responseXML
はブラウザごとに異なります。Firefox では、nsIDOMDocument
IEでは、IXMLDOMDocument
Webkit ブラウザではresponseType
設定によって異なりますが、おそらくDocument
. それがどうなるか予測できないので、それを拡張しようとするのをやめてください。ほとんどの場合、タイプはブラウザーの API によって使用可能にされていないため、javascript はとにかくそれを拡張できません。
さらに、JavaScript の継承はクラス ベースではないため、次のようにする必要があります。
XMLHandler.prototype = new XMLDocument();
...これは単に目的のために機能しません。のインスタンスはXMLHandler
、 によって返されるドキュメントではなく、関連のない空のドキュメントに基づいて構築されresponseXML
ます。ここではラッパーを使用する必要があります。
2 番目の質問:
3 つのメソッドのうち、最初のメソッドは最後のメソッドと同等ですが、同じ関数を同じプロトタイプに繰り返し設定するため、無駄が多くなります。2 番目は意味がなく、構文が壊れています。これらはあなたの本当の選択肢です:
// Instance method, every instance is given a copy of the function upon "new"
function MyClass()
{
this.publicFunct = function()
{
alert("public function");
};
}
// Prototypal method, only one copy of the function shared by all instances
function MyClass()
{
}
MyClass.prototype.publicFunct = function()
{
alert("public function");
};
// Shorthand method, same as prototypal but handy for several members at once
// It prevents MyClass from being a descendent of another type
function MyClass()
{
}
MyClass.prototype = {
// A colon is only acceptable in object notation
publicFunct: function()
{
alert("public function");
}
};
クラスに関数を選択的に追加する必要がない限り、効率のためにプロトタイプの方法を使用します。「パブリック関数」(「クラス」も) の使用は、OOP バックグラウンドの別の症状のように思えます。JavaScript にはプライベート関数がないため、「パブリック」には場所がなく、すべてのメンバー関数はパブリックです。ある時点でプライベート関数が必要な場合は、クロージャーで効果を偽造できます。
(function() {
// Assignments are mostly global
MyClass = function() {};
MyClass.prototype.publicFunct = function()
{
privateFunct();
};
// These statements affect local scope
var foo = 'bar';
function privateFunct()
{
alert("public function");
}
})(); // These extra brackets cause the contents to be executed immediately
プライベート関数が必要になることはめったになく、とにかくすべての JavaScript が表示されるので、実際には秘密ではありません。上記は次のように妨害される可能性があります。
thief = {};
MyClass.prototype.publicFunct.call(thief);
// privateFunct is called by publicFunct in the context of the thief
関数がパブリックであることを受け入れることもできます。さらに一歩進んで、クラスを完全にあきらめることができます。オブジェクトはたまたまいくつかの機能を持つオブジェクトであり、それらの機能は完全に異なるオブジェクトと共有することさえできます。