這件事幾乎工程:JavaScript類調用XMLHttpRequest的內部,再經手的onreadystatechange
function myClass(url) {
this.source = url;
this.rq = null;
this.someOtherProperty = "hello";
// open connection to the ajax server
this.start = function() {
if (window.XMLHttpRequest) {
this.rq = new XMLHttpRequest();
if (this.rq.overrideMimeType)
this.rq.overrideMimeType("text/xml");
} else
this.rq = new ActiveXObject("Microsoft.XMLHTTP");
try {
this.rq.onreadystatechange = connectionEvent;
this.rq.open("GET", this.source, true);
this.rq.send(null);
this.state = 1;
} catch (err) {
// some error handler here
}
}
function connectionEvent() {
alert("i'm here");
alert("this doesnt work: " + this.someOtherProperty);
}
} // MyClass的
所以它不是什麼比XMLHttpRequest對象爲我的類的成員多,全局定義,並以傳統方式調用它。然而,在我的connectionEvent回調函數中,「this」的含義會丟失,即使函數本身在myClass中有作用域。我還確保從myClass實例化的對象保持足夠長的活動時間(在腳本中聲明爲全局對象)。
在我看到的所有使用javascript類的示例中,「this」在內部函數中仍然可用。對我來說,這不是,即使我把我的函數放在外面,並將其設置爲myClass.prototype.connectionEvent。我究竟做錯了什麼?謝謝。
使用jQuery偉大的Ajax。 – sundowatch 2010-05-14 18:07:22
歡迎在Stackoverflow :)而是使用4個空格而不是每個縮進的選項卡。然後,當你在這裏複製代碼時,你必須用另外4個空格縮進*完整*片段。你可以通過選擇一塊,然後按消息編輯器工具欄中的'010101'按鈕或'Ctrl + K'鍵來完成。 – BalusC 2010-05-14 18:10:30