- 1、学习目标
- 2、源码地址
- 3、源码阅读
- 3.1 isArray 判断数组
- 3.2 isUndefined 判断 Undefined
- 3.3 isBuffer 判断 buffer
- 3.4 isArrayBuffer 判断 ArrayBuffer
- 3.5 isFormData 判断FormData
- 3.6 isArrayBufferView 判断ArrayBuffer视图的实例
- 3.7 isString 判断字符串
- 3.8 isNumber 判断数字
- 3.9 isObject 判断对象
- 3.10 isPlainObject 判断纯对象
- 3.11 isDate 判断Date
- 3.12 isFile 判断文件类型
- 3.13 isBlob 判断Blob
- 3.14 isFunction 判断函数
- 3.15 isStream 判断是否是流
- 3.16 isURLSearchParams 判断URLSearchParams
- 3.17 trim 去除首尾空格
- 3.18 isStandardBrowserEnv 判断标准浏览器环境
- 3.19 forEach 遍历对象或数组
- 3.20 merge 合并对象
- 3.21 extend 继承
- 3.22 stripBOM 删除UTF-8编码中BOM
- 4、总结
1、学习目标
- 学习axios源码中实用的工具函数
- 积累常用的工具函数,可在自己的项目中应用。
2、源码地址
3、源码阅读
3.1 isArray 判断数组
/*** Determine if a value is an Array** @param {Object} val The value to test* @returns {boolean} True if value is an Array, otherwise false*/function isArray(val) {return Array.isArray(val);}
3.2 isUndefined 判断 Undefined
/*** Determine if a value is undefined** @param {Object} val The value to test* @returns {boolean} True if the value is undefined, otherwise false*/function isUndefined(val) {return typeof val === 'undefined';}
3.3 isBuffer 判断 buffer
什么是Buffer?
JavaScript 语言自身只有字符串数据类型,没有二进制数据类型。但在处理像TCP流或文件流时,必须使用到二进制数据。
因此在 Node.js中,定义了一个Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。详细可以看 官方文档 或 更通俗易懂的解释。
/*** Determine if a value is a Buffer** @param {Object} val The value to test* @returns {boolean} True if value is a Buffer, otherwise false*/function isBuffer(val) {return val !== null&& !isUndefined(val) // 先判断不是 `undefined`和`null`&& val.constructor !== null&& !isUndefined(val.constructor) // 再判断 `val`存在构造函数,因为`Buffer`本身是一个类&& typeof val.constructor.isBuffer === 'function'&& val.constructor.isBuffer(val);}
3.4 isArrayBuffer 判断 ArrayBuffer
/*** Determine if a value is an ArrayBuffer** @param {Object} val The value to test* @returns {boolean} True if value is an ArrayBuffer, otherwise false*/function isArrayBuffer(val) {return toString.call(val) === '[object ArrayBuffer]';}
3.5 isFormData 判断FormData
// `instanceof` 运算符用于检测构造函数的 `prototype` 属性是否出现在某个实例对象的原型链上function isFormData(val) {return (typeof FormData !== 'undefined') && (val instanceof FormData);}/*** Determine if a value is a FormData** @param {Object} val The value to test* @returns {boolean} True if value is an FormData, otherwise false*/function isFormData(val) {return toString.call(val) === '[object FormData]';}
3.6 isArrayBufferView 判断ArrayBuffer视图的实例
/*** Determine if a value is a view on an ArrayBuffer** @param {Object} val The value to test* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false*/function isArrayBufferView(val) {var result;if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {result = ArrayBuffer.isView(val);} else {result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));}return result;}
3.7 isString 判断字符串
/*** Determine if a value is a String** @param {Object} val The value to test* @returns {boolean} True if value is a String, otherwise false*/function isString(val) {return typeof val === 'string';}
3.8 isNumber 判断数字
/*** Determine if a value is a Number** @param {Object} val The value to test* @returns {boolean} True if value is a Number, otherwise false*/function isNumber(val) {return typeof val === 'number';}
3.9 isObject 判断对象
// 排除 `null`的情况function isObject(val) {return val !== null && typeof val === 'object';}
3.10 isPlainObject 判断纯对象
纯对象: 用{}或new Object()创建的对象。
其实就是判断目标对象的原型是不是**null** 或 **Object.prototype**
/*** Determine if a value is a plain Object** @param {Object} val The value to test* @return {boolean} True if value is a plain Object, otherwise false*/function isPlainObject(val) {if (toString.call(val) !== '[object Object]') {return false;}var prototype = Object.getPrototypeOf(val);return prototype === null || prototype === Object.prototype;}
3.11 isDate 判断Date
/*** Determine if a value is a Date** @param {Object} val The value to test* @returns {boolean} True if value is a Date, otherwise false*/function isDate(val) {return toString.call(val) === '[object Date]';}
3.12 isFile 判断文件类型
/*** Determine if a value is a File** @param {Object} val The value to test* @returns {boolean} True if value is a File, otherwise false*/function isFile(val) {return toString.call(val) === '[object File]';}
3.13 isBlob 判断Blob
Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取。
/*** Determine if a value is a Blob** @param {Object} val The value to test* @returns {boolean} True if value is a Blob, otherwise false*/function isBlob(val) {return toString.call(val) === '[object Blob]';}
3.14 isFunction 判断函数
/*** Determine if a value is a Function** @param {Object} val The value to test* @returns {boolean} True if value is a Function, otherwise false*/function isFunction(val) {return toString.call(val) === '[object Function]';}
3.15 isStream 判断是否是流
/*** Determine if a value is a Stream** @param {Object} val The value to test* @returns {boolean} True if value is a Stream, otherwise false*/function isStream(val) {return isObject(val) && isFunction(val.pipe);}
3.16 isURLSearchParams 判断URLSearchParams
/*** Determine if a value is a URLSearchParams object** @param {Object} val The value to test* @returns {boolean} True if value is a URLSearchParams object, otherwise false*/function isURLSearchParams(val) {return toString.call(val) === '[object URLSearchParams]';}// 例子const paramsString = "q=URLUtils.searchParams&topic=api"const searchParams = new URLSearchParams(paramsString);isURLSearchParams(searchParams) // true
URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串,详情可看 MDN:
var paramsString = "q=URLUtils.searchParams&topic=api"var searchParams = new URLSearchParams(paramsString);for (let p of searchParams) {console.log(p);}// 输出[ 'q', 'URLUtils.searchParams' ][ 'topic', 'api' ]searchParams.has("topic") === true; // truesearchParams.get("topic") === "api"; // truesearchParams.getAll("topic"); // ["api"]searchParams.get("foo") === null; // truesearchParams.append("topic", "webdev");searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"searchParams.set("topic", "More webdev");searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"searchParams.delete("topic");searchParams.toString(); // "q=URLUtils.searchParams"
3.17 trim 去除首尾空格
// `trim`方法不存在的话,用正则/*** Trim excess whitespace off the beginning and end of a string** @param {String} str The String to trim* @returns {String} The String freed of excess whitespace*/function trim(str) {return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');}
3.18 isStandardBrowserEnv 判断标准浏览器环境
/*** Determine if we're running in a standard browser environment** This allows axios to run in a web worker, and react-native.* Both environments support XMLHttpRequest, but not fully standard globals.** web workers:* typeof window -> undefined* typeof document -> undefined** react-native:* navigator.product -> 'ReactNative'* nativescript* navigator.product -> 'NativeScript' or 'NS'*/function isStandardBrowserEnv() {if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||navigator.product === 'NativeScript' ||navigator.product === 'NS')) {return false;}return (typeof window !== 'undefined' &&typeof document !== 'undefined');}
但是官方已经不推荐使用这个属性navigator.product。
3.19 forEach 遍历对象或数组
/*** Iterate over an Array or an Object invoking a function for each item.* 用一个函数去迭代数组或对象** If `obj` is an Array callback will be called passing* the value, index, and complete array for each item.* 如果是数组,回调将会调用value, index, 和整个数组** If 'obj' is an Object callback will be called passing* the value, key, and complete object for each property.* 如果是对象,回调将会调用value, key, 和整个对象** @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// 如果值不存在,无需处理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];}if (isArray(obj)) {// Iterate over array values// 是数组,for循环执行回调fnfor (var i = 0, l = obj.length; i < l; i++) {fn.call(null, obj[i], i, obj);}} else {// Iterate over object keys// 是对象,for循环执行回调fnfor (var key in obj) {// 只遍历可枚举属性if (Object.prototype.hasOwnProperty.call(obj, key)) {fn.call(null, obj[key], key, obj);}}}}
3.20 merge 合并对象
合并多个对象,如果其中有相同的键名,则后面的值取代前面的值
/*** Accepts varargs expecting each argument to be an object, then* immutably merges the properties of each object and returns result.** When multiple objects contain the same key the later object in* the arguments list will take precedence.** Example:** ```js* var result = merge({foo: 123}, {foo: 456});* console.log(result.foo); // outputs 456*
*
- @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、总结
- 积累一些实用的工具函数,并把这些代码或思想应用的自己项目中去。
- 学习如何注释一个函数。
