[js] axios为什么可以使用对象和函数两种方式调用?是如何实现的?

axios 源码 初始化
看源码第一步,先看package.json。一般都会申明 main 主入口文件。
// package.json
{
“name”: “axios”,
“version”: “0.19.0”,
“description”: “Promise based HTTP client for the browser and node.js”,
“main”: “index.js”,
// …
}
复制代码
主入口文件
// index.js
module.exports = require(’./lib/axios’);
复制代码
4.1 lib/axios.js主文件
axios.js文件 代码相对比较多。分为三部分展开叙述。

第一部分:引入一些工具函数utils、Axios构造函数、默认配置defaults等。
第二部分:是生成实例对象 axios、axios.Axios、axios.create等。
第三部分取消相关API实现,还有all、spread、导出等实现。

4.1.1 第一部分
引入一些工具函数utils、Axios构造函数、默认配置defaults等。
// 第一部分:
// lib/axios
// 严格模式
‘use strict’;
// 引入 utils 对象,有很多工具方法。
var utils = require(’./utils’);
// 引入 bind 方法
var bind = require(’./helpers/bind’);
// 核心构造函数 Axios
var Axios = require(’./core/Axios’);
// 合并配置方法
var mergeConfig = require(’./core/mergeConfig’);
// 引入默认配置
var defaults = require(’./defaults’);
复制代码
4.1.2 第二部分
是生成实例对象 axios、axios.Axios、axios.create等。
/**

  • Create an instance of Axios
  • @param {Object} defaultConfig The default config for the instance
  • @return {Axios} A new instance of Axios
    */
    function createInstance(defaultConfig) {
    // new 一个 Axios 生成实例对象
    var context = new Axios(defaultConfig);
    // bind 返回一个新的 wrap 函数,
    // 也就是为什么调用 axios 是调用 Axios.prototype.request 函数的原因
    var instance = bind(Axios.prototype.request, context);
    // Copy axios.prototype to instance
    // 复制 Axios.prototype 到实例上。
    // 也就是为什么 有 axios.get 等别名方法,
    // 且调用的是 Axios.prototype.get 等别名方法。
    utils.extend(instance, Axios.prototype, context);
    // Copy context to instance
    // 复制 context 到 intance 实例
    // 也就是为什么默认配置 axios.defaults 和拦截器 axios.interceptors 可以使用的原因
    // 其实是new Axios().defaults 和 new Axios().interceptors
    utils.extend(instance, context);
    // 最后返回实例对象,以上代码,在上文的图中都有体现。这时可以仔细看下上图。
    return instance;
    }

// Create the default instance to be exported
// 导出 创建默认实例
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
// 暴露 Axios class 允许 class 继承 也就是可以 new axios.Axios()
// 但 axios 文档中 并没有提到这个,我们平时也用得少。
axios.Axios = Axios;

// Factory for creating new instances
// 工厂模式 创建新的实例 用户可以自定义一些参数
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
复制代码
这里简述下工厂模式。axios.create,也就是用户不需要知道内部是怎么实现的。
举个生活的例子,我们买手机,不需要知道手机是怎么做的,就是工厂模式。
看完第二部分,里面涉及几个工具函数,如bind、extend。接下来讲述这几个工具方法。
4.1.3 工具方法之 bind
axios/lib/helpers/bind.js
‘use strict’;
// 返回一个新的函数 wrap
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
// 把 argument 对象放在数组 args 里
return fn.apply(thisArg, args);
};
};
复制代码
传递两个参数函数和thisArg指向。
把参数arguments生成数组,最后调用返回参数结构。
其实现在 apply 支持 arguments这样的类数组对象了,不需要手动转数组。
那么为啥作者要转数组,为了性能?当时不支持?抑或是作者不知道?这就不得而知了。有读者知道欢迎评论区告诉笔者呀。
关于apply、call和bind等不是很熟悉的读者,可以看笔者的另一个面试官问系列。
面试官问:能否模拟实现JS的bind方法
举个例子
function fn(){
console.log.apply(console, arguments);
}
fn(1,2,3,4,5,6, ‘若川’);
// 1 2 3 4 5 6 ‘若川’
复制代码
4.1.4 工具方法之 utils.extend
axios/lib/utils.js
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === ‘function’) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
复制代码
其实就是遍历参数 b 对象,复制到 a 对象上,如果是函数就是则用 bind 调用。
4.1.5 工具方法之 utils.forEach
axios/lib/utils.js
遍历数组和对象。设计模式称之为迭代器模式。很多源码都有类似这样的遍历函数。比如大家熟知的jQuery $.each。
/**

  • @param {Object|Array} obj The object to iterate
  • @param {Function} fn The callback to invoke for each item
    */
    function forEach(obj, fn) {
    // Don’t bother if no value provided
    // 判断 null 和 undefined 直接返回
    if (obj === null || typeof obj === ‘undefined’) {
    return;
    }

// Force an array if not already something iterable
// 如果不是对象,放在数组里。
if (typeof obj !== ‘object’) {
/eslint no-param-reassign:0/
obj = [obj];
}

// 是数组 则用for 循环,调用 fn 函数。参数类似 Array.prototype.forEach 的前三个参数。
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
// 用 for in 遍历对象,但 for in 会遍历原型链上可遍历的属性。
// 所以用 hasOwnProperty 来过滤自身属性了。
// 其实也可以用Object.keys来遍历,它不遍历原型链上可遍历的属性。
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
复制代码
如果对Object相关的API不熟悉,可以查看笔者之前写过的一篇文章。JavaScript 对象所有API解析
4.1.6 第三部分
取消相关API实现,还有all、spread、导出等实现。
// Expose Cancel & CancelToken
// 导出 Cancel 和 CancelToken
axios.Cancel = require(’./cancel/Cancel’);
axios.CancelToken = require(’./cancel/CancelToken’);
axios.isCancel = require(’./cancel/isCancel’);

// Expose all/spread
// 导出 all 和 spread API
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require(’./helpers/spread’);

module.exports = axios;

// Allow use of default import syntax in TypeScript
// 也就是可以以下方式引入
// import axios from ‘axios’;
module.exports.default = axios;
复制代码
这里介绍下 spread,取消的API暂时不做分析,后文再详细分析。
假设你有这样的需求。
function f(x, y, z) {}
var args = [1, 2, 3];
f.apply(null, args);
复制代码
那么可以用spread方法。用法:
axios.spread(function(x, y, z) {})([1, 2, 3]);
复制代码
实现也比较简单。源码实现:
/**

  • @param {Function} callback
  • @returns {Function}
    */
    module.exports = function spread(callback) {
    return function wrap(arr) {
    return callback.apply(null, arr);
    };
    };
    复制代码
    上文var context = new Axios(defaultConfig);,接下来介绍核心构造函数Axios。
    4.2 核心构造函数 Axios
    axios/lib/core/Axios.js
    构造函数Axios。
    function Axios(instanceConfig) {
    // 默认参数
    this.defaults = instanceConfig;
    // 拦截器 请求和响应拦截器
    this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
    };
    }
    复制代码
    Axios.prototype.request = function(config){
    // 省略,这个是核心方法,后文结合例子详细描述
    // code …
    var promise = Promise.resolve(config);
    // code …
    return promise;
    }
    // 这是获取 Uri 的函数,这里省略
    Axios.prototype.getUri = function(){}
    // 提供一些请求方法的别名
    // Provide aliases for supported request methods
    // 遍历执行
    // 也就是为啥我们可以 axios.get 等别名的方式调用,而且调用的是 Axios.prototype.request 方法
    // 这个也在上面的 axios 结构图上有所体现。
    utils.forEach([‘delete’, ‘get’, ‘head’, ‘options’], function forEachMethodNoData(method) {
    /eslint func-names:0/
    Axios.prototype[method] = function(url, config) {
    return this.request(utils.merge(config || {}, {
    method: method,
    url: url
    }));
    };
    });

utils.forEach([‘post’, ‘put’, ‘patch’], function forEachMethodWithData(method) {
/eslint func-names:0/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});

module.exports = Axios;
复制代码
接下来看拦截器部分。
4.3 拦截器管理构造函数 InterceptorManager
请求前拦截,和请求后拦截。
在Axios.prototype.request函数里使用,具体怎么实现的拦截的,后文配合例子详细讲述。
axios github 仓库 拦截器文档
如何使用:
// Add a request interceptor
// 添加请求前拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

// Add a response interceptor
// 添加请求后拦截器
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
复制代码
如果想把拦截器,可以用eject方法。
const myInterceptor = axios.interceptors.request.use(function () {//});
axios.interceptors.request.eject(myInterceptor);
复制代码
拦截器也可以添加自定义的实例上。
const instance = axios.create();
instance.interceptors.request.use(function () {//});
复制代码
源码实现:
构造函数,handles 用于存储拦截器函数。
function InterceptorManager() {
this.handlers = [];
}
复制代码
接下来声明了三个方法:使用、移除、遍历。
4.3.1 InterceptorManager.prototype.use 使用
传递两个函数作为参数,数组中的一项存储的是{fulfilled: function(){}, rejected: function(){}}。返回数字 ID,用于移除拦截器。
/**

  • @param {Function} fulfilled The function to handle then for a Promise
  • @param {Function} rejected The function to handle reject for a Promise
  • @return {Number} 返回ID 是为了用 eject 移除
    /
    InterceptorManager.prototype.use = function use(fulfilled, rejected) {
    this.handlers.push({
    fulfilled: fulfilled,
    rejected: rejected
    });
    return this.handlers.length - 1;
    };
    复制代码
    4.3.2 InterceptorManager.prototype.eject 移除
    根据 use 返回的 ID 移除 拦截器。
    /
    *
  • @param {Number} id The ID that was returned by use
    /
    InterceptorManager.prototype.eject = function eject(id) {
    if (this.handlers[id]) {
    this.handlers[id] = null;
    }
    };
    复制代码
    有点类似定时器setTimeout 和 setInterval,返回值是id。用clearTimeout 和clearInterval来清除定时器。
    // 提一下 定时器回调函数是可以传参的,返回值 timer 是数字
    var timer = setInterval((name) => {
    console.log(name);
    }, 1000, ‘若川’);
    console.log(timer); // 数字 ID
    // 在控制台等会再输入执行这句,定时器就被清除了
    clearInterval(timer);
    复制代码
    4.3.3 InterceptorManager.prototype.forEach 遍历
    遍历执行所有拦截器,传递一个回调函数(每一个拦截器函数作为参数)调用,被移除的一项是null,所以不会执行,也就达到了移除的效果。
    /
    *
  • @param {Function} fn The function to call for each interceptor
    */
    InterceptorManager.prototype.forEach = function forEach(fn) {
    utils.forEach(this.handlers, function forEachHandler(h) {
    if (h !== null) {
    fn(h);
    }
    });
    };
    复制代码
  1. 实例结合
    上文叙述的调试时运行npm start 是用axios/sandbox/client.html路径的文件作为示例的,读者可以自行调试。
    以下是一段这个文件中的代码。
    axios(options)
    .then(function (res) {
    response.innerHTML = JSON.stringify(res.data, null, 2);
    })
    .catch(function (res) {
    response.innerHTML = JSON.stringify(res.data, null, 2);
    });

个人简介

我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论

主目录

与歌谣一起通关前端面试题