XMLDocument的Javascript子类不起作用

时间:2011-11-06 01:35:42

标签: javascript inheritance prototype-programming

我试图制作原型(我认为这就是所谓的)&在Javascript中执行继承。希望它遵循Javascript的惯例。

应该改变什么以使其起作用&这是正确的JavaScript编码?代码现在不能编译/工作

我正在尝试创建一个跨浏览器XML解析器。所以我尝试“子类化”XMLDocument对象,虽然我不确定该对象是否存在,但是当我调用函数xmlHttp.responseXML时,我试图将对象子类化(从XMLHttpRequest()对象返回);

一件重要的事情是我想坚持本土的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 );
     }
  }

1 个答案:

答案 0 :(得分:0)

  1. Javascript IS EcmaScript。 任何您在 名称下学习任何版本都很有价值。不要试图“避开”。

  2. 出于同样的原因,如果您认为可以帮助完成任务,请不要害怕接受jQuery或Dojo。

  3. “避开”任何先入为主的“继承”概念,或“跨平台”可能意味着什么或不具有什么意义。

  4. 只关注你的目标。究竟,你想要完成什么?不是“如何”(例如“继承”),而是“ WHAT ”(例如“我想解析这个XML文件,以便我可以在网页中显示一些信息”)。

  5. 恕我直言.. PSM

    PS: 你的Javascript“没有编译”???你到底是什么意思?

    PPS: 如果您来自C ++或Java,那么您对“继承”的一些先入之见 - 或者,就此而言,“面向对象”,可能实际上更有害而不是好。获取Douglas Crockford最优秀的“Javascript:The Good Parts”的副本;)