<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios模拟过程</title>
</head>
<body>
<script>
// 构造函数
function Axios(config) {
// 初始化
this.defaults = config;
this.interceptors = {
request: {},
response: {}
}
}
// 原型添加相关的方法
Axios.prototype.request = function(config) {
console.log('发送AJAX请求, 请求类型为: ' + config.method);
}
Axios.prototype.get = function(config) {
this.request({method: "GET"});
}
Axios.prototype.post = function(config) {
this.request({method: "POST"});
}
// 声明函数
function createInstance(config) {
// 实例化一个对象,可以执行context.get() context.post(),但是不能当函数使用 context()
let context = new Axios(config);
// 创建请求函数, instance 是一个函数,并且可以执行 instance({}), 此时instance不能使用 instance.get() instance.post()
let instance = Axios.prototype.request.bind(context);
// 将Axios.prototype对象中的方法添加到instance函数对象中
Object.keys(Axios.prototype).forEach(key => {
// console.log(key);
instance[key] = Axios.prototype[key].bind(context); // this.default this.interceptors
})
// console.dir(instance);
// 为instance 函数对象添加属性 default 与 interceptors
Object.keys(context).forEach(key => {
// console.log(key);
instance[key] = context[key];
})
// console.dir(instance);
return instance;
}
let axios = createInstance()
// 发送请求
axios({method: 'GET'})
axios({method: 'POST'})
axios.get({});
axios.post({});
</script>
</body>
</html>
模拟axios过程
最新推荐文章于 2023-10-14 11:25:20 发布