封裝 AJAX 物件時,使用 `xhr.onreadystatechange = this.response` 綁定回調。在 Chrome/Firefox/Opera/Safari 中 `this` 指向 `XMLHttpRequest` 物件,可直接讀取 `this.readyState`、`this.responseText`。但在 **IE6/7/8** 中,回調在**全域上下文**執行,`this === window`,導致邏輯失效 (無報錯、無回應)。
var Ajax = {
xhr: null,
callback: null,
connect: function(params) {
this.xhr = new XMLHttpRequest(); // 簡化
this.callback = params.callback;
this.xhr.onreadystatechange = this.response; // 關鍵綁定
this.xhr.open('GET', params.url, true);
this.xhr.send();
},
response: function() {
// 測試 this 指向
console.log('this === window:', this === window);
console.log('this instanceof XMLHttpRequest:', this instanceof XMLHttpRequest);
if (this.readyState === 4) { // IE 下 this 是 window,無 readyState
if (this.status === 200) {
Ajax.callback(this.responseText);
} else {
Ajax.callback(null, this.status);
}
}
}
};
| 瀏覽器 | `this === window` | `this instanceof XMLHttpRequest` | 結果 |
|---|---|---|---|
| Chrome/FF/Safari/Opera | false | true | 正常 |
| IE 6/7/8 | true | false | 失效 |
| IE 9+ | false | true | 正常 |
connect: function(params) {
var self = this; // 或 var xhr = this.xhr;
this.xhr = new XMLHttpRequest();
this.callback = params.callback;
this.xhr.onreadystatechange = function() {
// 這裡的 self/xhr 來自外層詞法作用域,不受 this 影響
if (self.xhr.readyState === 4) {
if (self.xhr.status === 200) {
self.callback(self.xhr.responseText);
} else {
self.callback(null, self.xhr.status);
}
}
};
this.xhr.open('GET', params.url, true);
this.xhr.send();
}
this.xhr.onreadystatechange = this.response.bind(this);
$.ajax({
url: params.url,
success: function(data) { params.callback(data); },
error: function(xhr) { params.callback(null, xhr.status); }
});