axios源码工具函数学习

8/21/2024 源码

# 源文件

使用的版本是1.7.4,文件目录 axios/lib/utils.js

git clone https://github.com/axios/axios.git
npm install
npm run start
1
2
3

# 工具函数

# isArray 判断是否为数组

Array.isArray
1

# isUndefined 判断是否为 undefined

直接用 type of 判断

const typeOfTest = (type) => (thing) => typeof thing === type
const isUndefined = typeOfTest('undefined')
// 同理判断是否为函数
const isFunction = typeOfTest('function')
1
2
3
4

# isBuffer 判断是否 buffer(二进制数据缓冲区)

/**
 * 先判断不上null和undefined,再判断 val存在构造函数,因为Buffer本身是一个类,最后通过自身的isBuffer方法判断
 */
function isBuffer(val) {
    return (
        val !== null &&
        isUndefined(val) &&
        val.constructor !== null &&
        !isUndefined(val.constructor) &&
        isFunction(val.constructor.isBuffer) &&
        val.constructor.isBuffer(val)
    )
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# kindOf 获取 JavaScript 数据类型名称的工具函数

const kindOf = ((cache) => (thing) => {
    const str = toString.call(thing)
    console.log('cache', cache)
    return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase())
})(Object.create(null))
1
2
3
4
5

# isFormData 判断

const isFormData = (thing) => {
    let kind
    return (
        thing &&
        ((typeof FormData === 'function' && thing instanceof FormData) ||
            (isFunction(thing.append) &&
                ((kind = kindOf(thing) === 'formData') ||
                    (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]'))))
    )
}
1
2
3
4
5
6
7
8
9
10
上次更新: 9/26/2024, 6:39:50 PM