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

[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);
    });

个人简介

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

主目录

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/413820.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot集成thymeleaf增删改查示例

有小伙伴找我要个 thymeleaf 的 demo&#xff0c;说自己集成的总是报错&#xff0c;所以就有了这篇… 关于什么是 thymeleaf 我就不赘述了&#xff0c;相信搜到这篇的大部分是奔着如何集成来的。 本文源码先附上&#xff1a;https://gitee.com/niceyoo/springboot-thymeleaf-…

转:基于TLS1.3的微信安全通信协议mmtls介绍

转自&#xff1a; https://mp.weixin.qq.com/s?__bizMzAwNDY1ODY2OQ&mid2649286266&idx1&snf5d049033e251cccc22e163532355ddf&scene0&keyb28b03434249256b2a5d4fdf323a185a798eaf972317ca3a47ef060d35c5cd8a4ae35715466d5bb5a558e424d20bef6c&ascene…

[js] 在不支持js的浏览器中如何隐藏JavaScript代码?

[js] 在不支持js的浏览器中如何隐藏JavaScript代码&#xff1f; 在<script>标签之后的代码中添加“<!-– ”&#xff0c;不带引号。 在</script>标签之前添加“// –->”,代码中没有引号。 旧浏览器现在将JavaScript代码视为一个长的HTML注释。而支持JavaSc…

慧联A8最新检测使用教程V2.0.3

有小伙伴反馈旧版本 TWS106、TWSVerification 软件无法检测慧联A8&#xff0c;如下方截图所示&#xff1a; 由于之前版本确实太低 1.0.5 或者 2.0.2 都无法检测慧联A8&#xff0c;需要安装 2.0.3 版本APP才可以检测&#xff0c;如下为慧联A8检测截图 2.0.3 版本APP&#xff1a;…

JS中的进制转换

1 前言 js的进制转换&#xff0c; 分为2进制&#xff0c;8进制&#xff0c;10进制&#xff0c;16进制之间的相互转换&#xff0c; 我们直接利用 对象.toString()即可实现。 仅作为记录。 2 代码 //10进制转为16进制 (10).toString(16) // >"a" //8进制转为16进制 …

工作307:uni-富文本的实现逻辑跳转

<template><view><jinEdit placeholder"请输入内容" editOk"editOk" uploadFileUrl"/#"></jinEdit></view> </template><script>import jinEdit from /components/jin-edit/jin-edit.vue;export defa…

非洛达芯片检测聚合教程NOT AIROHA CHIP

虽然发过如何使用mmi_ut检测耳机的文章了&#xff0c;但是仍有些小伙伴拿检测截图来问耳机啥版本&#xff0c;这次干脆直接把这段时间问的比较多的一些非洛达版本总结一下。顺道也给一些代理们看看&#xff0c;有些水平太差了。。。看固件都分不出啥版本来。。 注意&#xff1…

MyBatis:事务回滚

事务的隔离级别&#xff1a;DEFAULT、READ_UNCOMMITED、READ_COMMITTED、REPEATABLE_READ、SERIALIZABLE 事务的传播行为&#xff1a;REQUIRED、SUPPORTS、MANDATORY、REQUIRES_NEW、NOT_SUPPORTED、NEVER、NESTED 我们这里举一个小例子说明下&#xff0c;在一个service方法中执…

工作308:uni-设置请求参数

// 如果没有通过拦截器配置域名的话&#xff0c;可以在这里写上完整的URL(加上域名部分) //上传图片 let uploadUrl /uploadFile/file;//登录相关 let loginUrl /login/toLogin; let logoutUrl /login/logout;//市场相关url let fireMapUrl /marketfiles/findFireFighting;…

华强北耳机版本太多,不知道如何选购?

目前市面上太多版本华强北三代耳机了&#xff0c;细数的话不下7、8种&#xff0c;比如什么&#xff0c;豪锐原壳版本、公牛版本、悦虎版本、翼虎版本、慧联A6(106)版本、慧联A6pro、慧联A8等&#xff0c;当然还得加上什么佳和1562A、悦虎|艾创力1562F、1536U&#xff0c;亦或者…

verilog 除法器

verilog 除法器&#xff1a;利用二进制的除法翻译过来的硬件电路1.1 实现算法基于减法的除法器的算法&#xff1a; 对于32的无符号除法&#xff0c;被除数a除以除数b&#xff0c;他们的商和余数一定不会超过32位。首先将a转换成高32位为0&#xff0c;低32位为a的temp_a。…

[vue-element] ElementUI是怎么做表单验证的?在循环里对每个input验证怎么做呢?

[vue] ElementUI是怎么做表单验证的&#xff1f;在循环里对每个input验证怎么做呢&#xff1f; model 绑定表单数据,通过prop取表单数值,通过编写ref进行后台API验证 ,根据rules进行表单内容验证个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&…

华强北四代慧联A10|悦虎1562M怎么样?

1、什么是华强北四代耳机&#xff1f; 所谓的华强北四代&#xff0c;其实对标的是水果10.19新发布的半入耳的AirPods 3&#xff0c;在此之前 AirPods 2被称作二代&#xff0c;AirPods Pro 被称作 三代&#xff0c;由于发布的新版本叫 AirPods 3&#xff0c;所以为了加以区分&a…

selenium实现原理

selenium会调用各自浏览器API&#xff0c;会发出CommandExector指令。指令会以URl形式通过Http request 发送出去。开始时&#xff0c;初始化webdriver时会启用一个端口的web service。浏览器就是绑定此端口。就可以操作浏览器上的元素。并且浏览器会返回请求&#xff0c;就可以…

[vue-element] 你有二次封装过ElementUI组件吗?

[vue-element] 你有二次封装过ElementUI组件吗&#xff1f; popover button 的组件&#xff0c;点击该按钮后还有个二次确认或选择的交互。 InfiniteScroll 封装个简单的带触底加载的列表 <template><el-inputplaceholder"价格"v-model"current&quo…

洛达芯片公牛方案适配APP使用参考

1、一点废话&#xff0c;检测相关 不容易&#xff0c;吵吵嚷嚷的大半年&#xff0c;公牛版三代终于出适配安卓的App了&#xff0c;此后&#xff0c;安卓阵营又多了一个可供纠结&#xff08;选择&#xff09;的版本了 &#xff0c;截图几张比较重要的功能。 纠结选择咱先不管…

时间控件,选择日期

导包: <link rel"stylesheet" href"../../../css/mui.picker.min.css" /> <script src"../../../js/mui.picker.min.js"></script> rel"stylesheet"此属性必须要,否则格式会错误 <!--日期选择器--> <div c…

[vue-element] ElementUI怎么修改组件的默认样式?

[vue-element] ElementUI怎么修改组件的默认样式&#xff1f; 方法一&#xff1a;/deep/ 方法二&#xff1a;>>> 方法三&#xff1a;在外层添加一层div&#xff0c;设置自定义类名&#xff0c;再修改里边的样式, 格式.自定义类名 .需要修改的样式 {}。个人简介 我是…

悦虎四代洛达1562M固件下载升级更新

四代如何刷固件可以参考之前二代的&#xff0c;等后面有时间的话给大家录制个四代的升级视频&#xff1a; 二代刷机教程&#xff1a;http://www.71xun.com/index.php/archives/51 四代固件下载链接&#xff1a;http://nxw.so/6uddX 升级内容&#xff1a;适配悦虎APP flycc增…

module.exports和exports得区别

对module.exports和exports的一些理解 可能是有史以来最简单通俗易懂的有关Module.exports和exports区别的文章了。 exports module.exports {}; 所以module.exports和exports的区别就是var a{}; var ba;&#xff0c;a和b的区别 看起来木有什么太大区别&#xff0c;但实际用起…