class XHR {
constructor(beforeHooks = {}, afterHooks = {}) {
this.beforeHooks = beforeHooks;
this.afterHooks = afterHooks
this.xhr = window.XMLHttpRequest;
this.init()
}
init() {
let _this = this;
window.XMLHttpRequest = function () {
this._xhr = new _this.xhr();
_this.overwrite(this);
}
}
overwrite(newThis) {
for (let proto in newThis._xhr) {
if (typeof newThis._xhr[proto] === 'function') {
this.writeFunction(newThis, proto)
continue
}
this.writeAttributes(newThis, proto)
}
}
writeAttributes(newThis, proto) {
Object.defineProperty(newThis, proto, this.setdefineProoerty(newThis, proto))
}
setdefineProoerty(newThis, proto) {
let obj = Object.create(null);
let _this = this;
obj.set = function (val) {
if (!proto.startsWith('on')) {
newThis[`__${proto}`] = val;
return
}
if(_this.beforeHooks[proto]){
this._xhr[proto] = function(...arg){
_this.beforeHooks[proto].call(newThis)
val.apply(newThis,arg)
}
return
}
this._xhr[proto] = val
}
obj.get = function(){
return newThis[`__${proto}`] || this._xhr[proto]
}
return obj
}
writeFunction(newThis, proto) {
newThis[proto] = (...arg) => {
if (this.beforeHooks[proto] && this.beforeHooks[proto]()) {
return false
}
debugger
newThis._xhr[proto].apply(newThis, arg);
this.afterHooks[proto] && this.afterHooks[proto]()
}
}
}
new XHR({
open: function () {
console.log('open');
},
onload: function () {
console.log('onload')
},
onreadystatechange: function () {
console.log('onreadystatechange')
},
onerror: function () {
console.log('onerror')
}
})
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.baidu.com', true);
xhr.send();
xhr.onreadystatechange = function (res) {
consonle.log(res)
}