<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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(`请求方式为${config.method}`)
}
Axios.prototype.get = function (config = {}) {
config.method = 'GET';
return this.request(config);
}
Axios.prototype.post = function (config = {}) {
config.method = 'POST';
return this.request(config);
}
// 声明函数
function createInstance(config) {
// 实例化一个Axios对象
// 可以使用原型上的get、post、request方法,但是自己本身并不能当做函数使用(不能像源码中使用axios(config))
let context = new Axios(config);
// 创建请求函数,可以使用instance(config),但是不能使用context上的方法,利用bind使调用者为axios对象,而非windows对象
let instance = Axios.prototype.request.bind(context);
// 将Axios.prototype对象中的方法添加到instance函数对象中
// Object.keys(object)方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致 。
Object.keys(Axios.prototype).forEach(key => {
instance[key] = Axios.prototype[key].bind(context);
})
// 为instance对象添加属性 defaults、interceptors
Object.keys(context).forEach(key => {
instance[key] = context[key];
})
return instance;
}
let axios = createInstance({
method: 'GET'
});
console.dir(axios);
axios({
method: 'POST'
})
axios.get();
</script>
</body>
</html>