源码 axios 的创建过程模拟实现

1、在实例对象上添加两个属性:default(默认配置)  与 interscptors

        // //构造函数
        function Axios(config) {
            //初始化
            this.defaults = config;//为了创建 default 默认属性
            this.interceptors = {
                request: {},
                response: {}
            }
        }

2、在原型对象上添加方法

//原型添加相关的方法
        Axios.prototype.request = function (config) {
            console.log('发送 AJAX 请求 请求的类型为 ' + config.method);
        }
        Axios.prototype.get = function (config) {
            return this.request({ method: 'GET' });
        }
        Axios.prototype.post = function (config) {
            return this.request({ method: 'POST' });
        }

3、通过bind方法,将实例对象中的属性与方法添加到instance中,并将instance返回,实现将axios当作对象或方法使用。

        //声明函数
        function createInstance(config) {
            //实例化一个对象
            let context = new Axios(config);
            // context.get()  context.post()  但是不能当做函数使用 context() X
            //创建请求函数
            let instance = Axios.prototype.request.bind(context);
            // instance 是一个函数 并且可以 instance({})  此时 instance 不能 instance.get X
            //将 Axios.prototype 对象中的方法添加到instance函数对象中
         
            Object.keys(Axios.prototype).forEach(key => {
                instance[key] = Axios.prototype[key].bind(context);
            // this.default  this.interceptors
            });
            // //为 instance 函数对象添加属性 default 与 interceptors
            Object.keys(context).forEach(key => {
                instance[key] = context[key];
            });
            return instance;
        }

  let axios = createInstance();
        axios.get({});
        axios.post({});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大大大大白呢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值