【发布时间】:2011-11-06 01:35:41
【问题描述】:
我尝试创建原型(我认为这就是所谓的)并在 Javascript 中执行继承。希望它遵循 Javascript 的约定。
应该进行哪些更改才能使其正常工作以及正确的 javascript 编码?该代码现在无法编译/工作
我正在尝试创建一个跨浏览器 XML 解析器。所以我尝试对 XMLDocument 对象进行“子类化”,虽然我不确定该对象是否存在,但当我调用函数 xmlHttp.responseXML;
一件重要的事情是我想坚持使用原生 Javascript 并暂时避开 EcmaScript 5,直到我学习原生 javascript 方法来创建原型和执行继承。
// I intend to use the XMLHandler object like so:
var xml = XMLHandler("myXMLFile.xml");
var slides = xml.getElementsByTageName("slide");
function XMLHandler( /*string*/ xmlFilePath )
{
this.getXMLFile = function()
{
return this.xmlFile;
}
this.xmlFile = xmlFilePath;
this.parseXMLFile( this.xmlFile );
}
XMLHandler.prototype = new XMLDocument(); // is this enough to make the object inherit from the XMLDocument
XMLHandler.prototype.constructor = XMLDocument; // make XMLHandler call the base class constructor when created
if ( window.XMLHttpRequest )
{
XMLHandler.prototype.parseXMLFile = function( xmlFilePath )
{
this.xmlFile = xmlFilePath;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", this.xmlFile, false); //Open the file using the GET routine
xmlHttp.send(null); //Send request
this = xmlHttp.responseXML; //this object holds/is the document information now
}
}
else if ( window.ActiveXObject ) // if the current browser is an old version of IE
{
XMLHandler.prototype.parseXMLFile = function( xmlFilePath )
{
this.xmlFile = xmlFilePath;
var xmlHttp = new ActiveXObject("Microsoft.XMLDOM");
xmlHttp.async = "false"; // keep synchronous for now
this = xmlHttp.load( this.xmlFile );
}
}
【问题讨论】:
-
“代码现在无法编译/工作” - 您遇到的确切问题是什么?什么不工作?
-
通过在
new关键字前面加上前缀来初始化“类”:var xml = new XMLHandler("myXMLFile.xml");
标签: javascript inheritance prototype-programming