【问题标题】:Javascript subclass of XMLDocument doesn't workXMLDocument 的 Javascript 子类不起作用
【发布时间】: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


【解决方案1】:
  1. Javascript IS EcmaScript。 任何你在任何一个名称下的任何版本都将是有价值的。不要试图“避开”。

  2. 同样,如果您认为 jQuery 或 Dojo 对您的任务有帮助,请不要害羞。

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

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

恕我直言..PSM

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

PPS: 如果您来自 C++ 或 Java,那么您对“继承”或“面向对象”的一些先入之见实际上可能弊大于利。获取 Douglas Crockford 最优秀的“Javascript:优秀部分”的副本;)

【讨论】:

    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多