3 回答

TA贡献2039条经验 获得超7个赞
可接受的答案几乎是正确的,但是可以稍作改进:
(function(open) {
XMLHttpRequest.prototype.open = function() {
this.addEventListener("readystatechange", function() {
console.log(this.readyState);
}, false);
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
优先使用apply + arguments而不是call,因为这样您就不必显式地知道打开的所有可能改变的参数!

TA贡献1804条经验 获得超2个赞
如何修改XMLHttpRequest.prototype.open或发送替换方法来设置自己的回调并调用原始方法?回调可以执行其操作,然后将回调称为指定的原始代码。
换一种说法:
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;
var myOpen = function(method, url, async, user, password) {
//do whatever mucking around you want here, e.g.
//changing the onload callback to your own version
//call original
this.realOpen (method, url, async, user, password);
}
//ensure all XMLHttpRequests use our custom open method
XMLHttpRequest.prototype.open = myOpen ;
添加回答
举报