2011-11-06 26 views
0

我試圖創建原型(我認爲是它叫什麼)&在Javascript進行繼承。希望它遵循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); 
    } 
    } 
+0

「的代碼不編譯/工作現在」 - 什麼是你有確切的問題?什麼不起作用? –

+0

通過爲'new'關鍵字加上前綴來初始化「類」:var xml = new XMLHandler(「myXMLFile.xml」);'' –

回答

0
  1. 的Javascript IS的EcmaScript。 任何你下要麼名稱爲學習任何將是有價值的。不要試圖「轉向清晰」。

  2. 同樣的道理,如果你認爲他們可能會與你的任務幫助別地拿起的jQuery或道場都害羞。

  3. 不要「避開」的「繼承」,或究竟是什麼「跨平臺」可能會或可能並不意味着任何先入爲主的觀念的。

  4. 只關注你的目標。你到底想要完成什麼?不是「如何」(例如用「繼承」),而是「WHAT」(例如「我想解析這個XML文件,以便我可以在網頁上顯示一些信息」)。

恕我直言.. PSM

PS: 你的JavaScript 「未編譯」 ???你到底什麼意思?

PPS: 如果您是來自C++或Java,那麼您對「繼承」的一些偏見 - 或者就此而言,「面向對象」,可能實際上比壞的更有害。獲取道格拉斯Crockford的最優秀的副本「的Javascript:好的部分」;)