2012-08-17 53 views
0

爲試用我的目的閱讀this mdn article about inheritance後,我想創造直接來自XMLHttpRequest的繼承像這樣的對象:JavaScript錯誤與繼承請求對象

function Request(url){ 
    XMLHttpRequest.call(this); 
}; 

Request.prototype = Object.create( 
    new XMLHttpRequest(),{ 
    'constructor' : { 
     'value' : Request, 
     'enumerable' : true 
    }, 

    'toString' : { 
     'value' : function(){ 
      return '[Object Request]'; 
     }, 
     'enumerable' : true 
    } 
}); 

這本身不會造成任何麻煩,但是當我嘗試使用一個實例。剛創建後調用繼承。開(方法,位置) - 方法使得瀏覽器拋出這個錯誤:

screenshot of error

有誰有一個想法,爲什麼這個錯誤是扔?我嘗試了與其他對象的繼承技術,它工作得很好,爲什麼不用XMLHttpRequest呢?

問候philipp

+0

簽出jQuery的.Ajax().Post().Get()方法他們已經做了類似於你想要的maby? – John 2012-08-17 14:05:34

+0

我知道jquery可以做所有事情,所以我想嘗試一下。 – philipp 2012-08-17 14:08:26

回答

1

大多數DOM構造函數不能被繼承。我不知道你沒有得到WRONG_THIS_ERROR ...

I tried this technique of inheritance with other Objects and it worked very fine

它適用於功能的構造,因爲他們.call method做類似的事情爲[[construct]]稱爲as a constructor with the new keyword什麼時候。

Why not with the XMLHttpRequest?

因爲它是天然的對象及其[[construct]]將調用一些本機代碼,而不是[[call]]荷蘭國際集團的功能體。其實[[call]]行爲將被定義爲像[[construct]]一樣工作,因此XMLHttpRequest可以在沒有new的情況下被調用,但也會返回一個新的實例。你可以嘗試xhr = XMLHttpRequest.call(anything) - 它不會改變anything,但返回一個新的對象。

而不是從它繼承(或甚至擴展本地原型),圍繞它構建一個包裝。