一次面试被问到的问题,当时没想起来,回来自己写了这个东西,轻拍。
function Axios(){
}
Axios.prototype.then = function (cal){
this.cal = cal
}
Axios.prototype.send = function(url, method, data){
//创建xml对象 调用open 调用send(用settimeout模拟)
var _this = this;
setTimeout(function(){
console.log(_this.cal)
_this.cal.call(this, 'data'+url)
},1000)
return this;
}
var axios = new Axios();
axios.send('url', 'method', 'data').then(function(data){
console.log(data);
});
大概意思就是:
- send和then方法放到原型上面
- then接受一个回调函数,这个回调函数有一个参数data
- 然后调用send里面写异步的请求,请求回来的回调函数(成功失败回调)调用then方法(this.then(function(data){处理data}))这样就把返回的数据传给then方法了。