1、学习目标

  • 学习axios源码中实用的工具函数
  • 积累常用的工具函数,可在自己的项目中应用。

2、源码地址

3、源码阅读

3.1 isArray 判断数组

  1. /**
  2. * Determine if a value is an Array
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is an Array, otherwise false
  6. */
  7. function isArray(val) {
  8. return Array.isArray(val);
  9. }

3.2 isUndefined 判断 Undefined

  1. /**
  2. * Determine if a value is undefined
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if the value is undefined, otherwise false
  6. */
  7. function isUndefined(val) {
  8. return typeof val === 'undefined';
  9. }

3.3 isBuffer 判断 buffer

什么是Buffer?
JavaScript 语言自身只有字符串数据类型,没有二进制数据类型。但在处理像TCP流或文件流时,必须使用到二进制数据。
因此在 Node.js中,定义了一个Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。详细可以看 官方文档 或 更通俗易懂的解释。

  1. /**
  2. * Determine if a value is a Buffer
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Buffer, otherwise false
  6. */
  7. function isBuffer(val) {
  8. return val !== null
  9. && !isUndefined(val) // 先判断不是 `undefined`和`null`
  10. && val.constructor !== null
  11. && !isUndefined(val.constructor) // 再判断 `val`存在构造函数,因为`Buffer`本身是一个类
  12. && typeof val.constructor.isBuffer === 'function'
  13. && val.constructor.isBuffer(val);
  14. }

3.4 isArrayBuffer 判断 ArrayBuffer

  1. /**
  2. * Determine if a value is an ArrayBuffer
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  6. */
  7. function isArrayBuffer(val) {
  8. return toString.call(val) === '[object ArrayBuffer]';
  9. }

3.5 isFormData 判断FormData

  1. // `instanceof` 运算符用于检测构造函数的 `prototype` 属性是否出现在某个实例对象的原型链上
  2. function isFormData(val) {
  3. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  4. }
  5. /**
  6. * Determine if a value is a FormData
  7. *
  8. * @param {Object} val The value to test
  9. * @returns {boolean} True if value is an FormData, otherwise false
  10. */
  11. function isFormData(val) {
  12. return toString.call(val) === '[object FormData]';
  13. }

3.6 isArrayBufferView 判断ArrayBuffer视图的实例

  1. /**
  2. * Determine if a value is a view on an ArrayBuffer
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  6. */
  7. function isArrayBufferView(val) {
  8. var result;
  9. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  10. result = ArrayBuffer.isView(val);
  11. } else {
  12. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  13. }
  14. return result;
  15. }

3.7 isString 判断字符串

  1. /**
  2. * Determine if a value is a String
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a String, otherwise false
  6. */
  7. function isString(val) {
  8. return typeof val === 'string';
  9. }

3.8 isNumber 判断数字

  1. /**
  2. * Determine if a value is a Number
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Number, otherwise false
  6. */
  7. function isNumber(val) {
  8. return typeof val === 'number';
  9. }

3.9 isObject 判断对象

  1. // 排除 `null`的情况
  2. function isObject(val) {
  3. return val !== null && typeof val === 'object';
  4. }

3.10 isPlainObject 判断纯对象

纯对象: 用{}或new Object()创建的对象。
其实就是判断目标对象的原型是不是**null** 或 **Object.prototype**

  1. /**
  2. * Determine if a value is a plain Object
  3. *
  4. * @param {Object} val The value to test
  5. * @return {boolean} True if value is a plain Object, otherwise false
  6. */
  7. function isPlainObject(val) {
  8. if (toString.call(val) !== '[object Object]') {
  9. return false;
  10. }
  11. var prototype = Object.getPrototypeOf(val);
  12. return prototype === null || prototype === Object.prototype;
  13. }

3.11 isDate 判断Date

  1. /**
  2. * Determine if a value is a Date
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Date, otherwise false
  6. */
  7. function isDate(val) {
  8. return toString.call(val) === '[object Date]';
  9. }

3.12 isFile 判断文件类型

  1. /**
  2. * Determine if a value is a File
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a File, otherwise false
  6. */
  7. function isFile(val) {
  8. return toString.call(val) === '[object File]';
  9. }

3.13 isBlob 判断Blob

Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取。

  1. /**
  2. * Determine if a value is a Blob
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Blob, otherwise false
  6. */
  7. function isBlob(val) {
  8. return toString.call(val) === '[object Blob]';
  9. }

3.14 isFunction 判断函数

  1. /**
  2. * Determine if a value is a Function
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Function, otherwise false
  6. */
  7. function isFunction(val) {
  8. return toString.call(val) === '[object Function]';
  9. }

3.15 isStream 判断是否是流

  1. /**
  2. * Determine if a value is a Stream
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a Stream, otherwise false
  6. */
  7. function isStream(val) {
  8. return isObject(val) && isFunction(val.pipe);
  9. }

3.16 isURLSearchParams 判断URLSearchParams

  1. /**
  2. * Determine if a value is a URLSearchParams object
  3. *
  4. * @param {Object} val The value to test
  5. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  6. */
  7. function isURLSearchParams(val) {
  8. return toString.call(val) === '[object URLSearchParams]';
  9. }
  10. // 例子
  11. const paramsString = "q=URLUtils.searchParams&topic=api"
  12. const searchParams = new URLSearchParams(paramsString);
  13. isURLSearchParams(searchParams) // true

URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串,详情可看 MDN:

  1. var paramsString = "q=URLUtils.searchParams&topic=api"
  2. var searchParams = new URLSearchParams(paramsString);
  3. for (let p of searchParams) {
  4. console.log(p);
  5. }
  6. // 输出
  7. [ 'q', 'URLUtils.searchParams' ]
  8. [ 'topic', 'api' ]
  9. searchParams.has("topic") === true; // true
  10. searchParams.get("topic") === "api"; // true
  11. searchParams.getAll("topic"); // ["api"]
  12. searchParams.get("foo") === null; // true
  13. searchParams.append("topic", "webdev");
  14. searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
  15. searchParams.set("topic", "More webdev");
  16. searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
  17. searchParams.delete("topic");
  18. searchParams.toString(); // "q=URLUtils.searchParams"

3.17 trim 去除首尾空格

  1. // `trim`方法不存在的话,用正则
  2. /**
  3. * Trim excess whitespace off the beginning and end of a string
  4. *
  5. * @param {String} str The String to trim
  6. * @returns {String} The String freed of excess whitespace
  7. */
  8. function trim(str) {
  9. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  10. }

3.18 isStandardBrowserEnv 判断标准浏览器环境

  1. /**
  2. * Determine if we're running in a standard browser environment
  3. *
  4. * This allows axios to run in a web worker, and react-native.
  5. * Both environments support XMLHttpRequest, but not fully standard globals.
  6. *
  7. * web workers:
  8. * typeof window -> undefined
  9. * typeof document -> undefined
  10. *
  11. * react-native:
  12. * navigator.product -> 'ReactNative'
  13. * nativescript
  14. * navigator.product -> 'NativeScript' or 'NS'
  15. */
  16. function isStandardBrowserEnv() {
  17. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  18. navigator.product === 'NativeScript' ||
  19. navigator.product === 'NS')) {
  20. return false;
  21. }
  22. return (
  23. typeof window !== 'undefined' &&
  24. typeof document !== 'undefined'
  25. );
  26. }

但是官方已经不推荐使用这个属性navigator.product。

3.19 forEach 遍历对象或数组

  1. /**
  2. * Iterate over an Array or an Object invoking a function for each item.
  3. * 用一个函数去迭代数组或对象
  4. *
  5. * If `obj` is an Array callback will be called passing
  6. * the value, index, and complete array for each item.
  7. * 如果是数组,回调将会调用value, index, 和整个数组
  8. *
  9. * If 'obj' is an Object callback will be called passing
  10. * the value, key, and complete object for each property.
  11. * 如果是对象,回调将会调用value, key, 和整个对象
  12. *
  13. * @param {Object|Array} obj The object to iterate
  14. * @param {Function} fn The callback to invoke for each item
  15. */
  16. function forEach(obj, fn) {
  17. // Don't bother if no value provided
  18. // 如果值不存在,无需处理
  19. if (obj === null || typeof obj === 'undefined') {
  20. return;
  21. }
  22. // Force an array if not already something iterable
  23. // 如果不是对象类型,强制转成数组类型
  24. if (typeof obj !== 'object') {
  25. /*eslint no-param-reassign:0*/
  26. obj = [obj];
  27. }
  28. if (isArray(obj)) {
  29. // Iterate over array values
  30. // 是数组,for循环执行回调fn
  31. for (var i = 0, l = obj.length; i < l; i++) {
  32. fn.call(null, obj[i], i, obj);
  33. }
  34. } else {
  35. // Iterate over object keys
  36. // 是对象,for循环执行回调fn
  37. for (var key in obj) {
  38. // 只遍历可枚举属性
  39. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  40. fn.call(null, obj[key], key, obj);
  41. }
  42. }
  43. }
  44. }

3.20 merge 合并对象

合并多个对象,如果其中有相同的键名,则后面的值取代前面的值

  1. /**
  2. * Accepts varargs expecting each argument to be an object, then
  3. * immutably merges the properties of each object and returns result.
  4. *
  5. * When multiple objects contain the same key the later object in
  6. * the arguments list will take precedence.
  7. *
  8. * Example:
  9. *
  10. * ```js
  11. * var result = merge({foo: 123}, {foo: 456});
  12. * console.log(result.foo); // outputs 456
  13. *

*

  • @param {Object} obj1 Object to merge
  • @returns {Object} Result of all merge properties / function merge(/ obj1, obj2, obj3, … */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } }

    for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } ```

    3.21 extend 继承

    ```javascript /**

  • Extends object a by mutably adding to it the properties of object b. *
  • @param {Object} a The object to be extended
  • @param {Object} b The object to copy properties from
  • @param {Object} thisArg The object to bind function to
  • @return {Object} The resulting value of object a */ 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; } ```

    3.22 stripBOM 删除UTF-8编码中BOM

    所谓 BOM,全称是Byte Order Mark,它是一个Unicode字符,通常出现在文本的开头,用来标识字节序。UTF-8主要的优点是可以兼容ASCII,但如果使用BOM的话,这个好处就没有了。 ```javascript /**
  • Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) *
  • @param {string} content with BOM
  • @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } ```

    4、总结

  • 积累一些实用的工具函数,并把这些代码或思想应用的自己项目中去。
  • 学习如何注释一个函数。