我可以告诉你最近的问题,你在想Java,但事实并非如此。
第一个问题:
responseXML
是每个浏览器不同。 Firefox给出nsIDOMDocument
,IE给出IXMLDOMDocument
并且Webkit浏览器依赖于responseType
setting,但可能是Document
。既然你无法预测它会停止试图扩展它。在大多数情况下,浏览器的API无法使用该类型,因此JavaScript无法扩展它。
而且,由于JavaScript的继承不是基于类的你是被迫这样做:
XMLHandler.prototype = new XMLDocument();
...这根本不适合你的目的的工作。 XMLHandler
的任何实例都将建立在不相关的空文档上,而不是由responseXML
返回的文档。你必须在这里使用包装。
第二个问题:
的3种方法的第一等同于最后更浪费的,因为它可重复设置同样的功能相同的原型。第二个是无意义的,语法被破坏。这些是你真正的选择:
// 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中没有任何私有函数,因此“public”没有位置,所有成员函数都是公共的。如果在某个时候你确实需要一个私人函数,你可以通过闭包伪造该效果。
(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
你可能会接受,功能是公开的。你可以进一步放弃课程。对象只是碰巧具有某些功能的对象,这些功能甚至可以与完全不同的对象共享。
SO是问答网站,而不是论坛。单独的问题应该是分开的。 – outis
请删除您的第二个问题,并通过右上角的Ask Question按钮将其重新发布为真正的第二个问题。 – BalusC