- 1. 前言
- 2. 工具函数
- 2.1 EMPTY_OBJ 空对象
- 2.2 DEV 环境变量
- 2.3 EMPTY_ARR 空数组
- 2.4 NOOP 空函数
- 2.5 NO 返回false的函数
- 2.6 isOn 判断字符串是否以on开头,并且on后首字母不是小写字母
- 2.7 isModelListener 监听器
- 2.8 extend = Object.assign
- 2.9 remove 移除数组中的一项
- 2.10 hasOwn 判断是不是自身拥有的属性
- 2.11 类型判断
- 2.12 isIntegerKey 判断是不是数字型的字符串key值
- 2.13 makeMap && isReservedProp
- 2.14 cacheStringFunction 缓存
- 2.15 一些正则函数
- 2.16 hasChanged 判断是否有变化
- 2.17 invokeArrayFns 执行数组里的函数,参数相同
- 2.18 def 定义对象属性
- 2.19 toNumber 转数字
- 2.20 getGlobalThis 全局对象
- 3. 总结
- 参考
1. 前言
1.1 调试环境
- 操作系统: macOS 11.5.2
- 浏览器: Chrome 94.0.4606.81
- shell: zsh (如何安装zsh,可以自行百度 ohmyzsh,windows系统需要使用WSL子系统安装)
- vue-next 3.2.4
- vscode 1.62.2
-
1.2 源码位置
克隆代码 git clone https://github.com/vuejs/vue-next.git, 在packages/shared/index.ts中
1.3 阅读该文章可以get以下知识点
Vue 3 源码 shared 模块中的一些实用工具函数
2. 工具函数
2.1 EMPTY_OBJ 空对象
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__? Object.freeze({}): {}EMPTY_OBJ.name = '11'// 赋值会报错// Cannot add property name, object is not extensible
Object.freeze方法冻结了对象,无法进行赋值操作,赋值会报错,但是做了环境区分,只针对dev环境
2.2 DEV 环境变量
// global.d.ts 全局声明// Global compile-time constantsdeclare var __DEV__: boolean// rollup.config.js 具体设置值import replace from '@rollup/plugin-replace'const replacements = {__DEV__: isBundlerESMBuild? // preserve to be handled by bundlers`(process.env.NODE_ENV !== 'production')`: // hard coded dev/prod builds!isProduction,}// allow inline overrides like//__RUNTIME_COMPILE__=true yarn build runtime-coreObject.keys(replacements).forEach(key => {if (key in process.env) {replacements[key] = process.env[key]}})return replace({// @ts-ignorevalues: replacements,preventAssignment: true})
环境变量DEV,在rollup.config.js中配置,使用了插件@rollup/plugin-replace,生成了全局环境变量,可以直接在代码中使用,这种用法可以学习一下在工具库中使用,需要结合rollup
2.3 EMPTY_ARR 空数组
// 和空对象EMPTY_OBJ一样,不能操作export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
2.4 NOOP 空函数
export const NOOP = () => {}// 很多库的源码中都有这样的定义函数,比如 jQuery、underscore、lodash 等// 使用场景:1. 方便判断, 2. 方便压缩// 1. 比如:const instance = {render: NOOP};// 条件const dev = true;if(dev){instance.render = function(){console.log('render');}}// 可以用作判断。if(instance.render === NOOP){console.log('i');}// 2. 再比如:// 方便压缩代码// 如果是 function(){} ,不方便压缩代码
2.5 NO 返回false的函数
/*** Always return false.*/export const NO = () => false// 方便压缩代码
2.6 isOn 判断字符串是否以on开头,并且on后首字母不是小写字母
const onRE = /^on[^a-z]/const isOn = (key: string) => onRE.test(key)// exapmle:isOn('onChange'); // trueisOn('onchange'); // falseisOn('on3change'); // true
正则 ^on 表示以on开头,[^a-z]表示on后面下一个字符不是小写
2.7 isModelListener 监听器
// 判断字符串是不是以onUpdate:开头export const isModelListener = (key: string) => key.startsWith('onUpdate:')
2.8 extend = Object.assign
// 合并 es5语法, 方便维护,如果需要对对象合并做一些操作,可以直接修改这里export const extend = Object.assign
2.9 remove 移除数组中的一项
// 移除el这一项,函数存在副作用,通过splice移除,没有返回新的数组export const remove = <T>(arr: T[], el: T) => {const i = arr.indexOf(el)if (i > -1) {arr.splice(i, 1)}}// example:const arr = [1, 2, 3];remove(arr, 3);console.log(arr); // [1, 2]
2.10 hasOwn 判断是不是自身拥有的属性
const hasOwnProperty = Object.prototype.hasOwnPropertyexport const hasOwn = (val: object,key: string | symbol): key is keyof typeof val => hasOwnProperty.call(val, key)// example:hasOwn({ a: undefined }, 'a') // truehasOwn({}, 'a') // falsehasOwn({}, 'hasOwnProperty') // falsehasOwn({}, 'toString') // false// 是自己的本身拥有的属性,不是通过原型链向上查找的。
2.11 类型判断
// 对象转化为字符串export const objectToString = Object.prototype.toString// 获取字符串的类型export const toTypeString = (value: unknown): string =>objectToString.call(value)// toTypeString 可以得到 "[object String]" 这种类型的字符串// 截取[object String]类型的String这一段,用来做类型判断export const toRawType = (value: unknown): string => {// extract "RawType" from strings like "[object RawType]"return toTypeString(value).slice(8, -1)}// 是不是纯粹的对象export const isPlainObject = (val: unknown): val is object =>toTypeString(val) === '[object Object]'// 判断是不是数组,伪数组不行export const isArray = Array.isArray// example:isArray([]); // trueisArray({0: 1, length: 1}); // false// 是不是map类型export const isMap = (val: unknown): val is Map<any, any> =>toTypeString(val) === '[object Map]'// 是不是set类型export const isSet = (val: unknown): val is Set<any> =>toTypeString(val) === '[object Set]'// 是不是Date类型export const isDate = (val: unknown): val is Date => val instanceof Date// 是不是function类型export const isFunction = (val: unknown): val is Function =>typeof val === 'function'// 是不是String类型export const isString = (val: unknown): val is string => typeof val === 'string'// 是不是Symbol类型export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'// 是不是object类型export const isObject = (val: unknown): val is Record<any, any> =>val !== null && typeof val === 'object'// 是不是Promise类型export const isPromise = <T = any>(val: unknown): val is Promise<T> => {return isObject(val) && isFunction(val.then) && isFunction(val.catch)}// 判断有没有then和catch方法// 基本数据类型可以通过typeof来判断,复杂数据类型,需要通过Object.prototype.toString.call的方式来判断
2.12 isIntegerKey 判断是不是数字型的字符串key值
export const isIntegerKey = (key: unknown) =>isString(key) &&key !== 'NaN' &&key[0] !== '-' &&'' + parseInt(key, 10) === key// example:isIntegerKey('a'); // falseisIntegerKey('0'); // trueisIntegerKey('011'); // falseisIntegerKey('11'); // true// parseInt第二个参数是进制,默认采用的是10进制
2.13 makeMap && isReservedProp
传入一个以逗号分隔的字符串,生成一个map(键值对),并返回一个函数检测key值是否存在map中,第二个参数将检测函数的key转换成小写
/*** Make a map and return a function for checking if a key* is in that map.* IMPORTANT: all calls of this function must be prefixed with* \/\*#\_\_PURE\_\_\*\/* So that rollup can tree-shake them if necessary.*/export function makeMap(str: string,expectsLowerCase?: boolean): (key: string) => boolean {// 返回一个空对象 {}const map: Record<string, boolean> = Object.create(null)// 字符串以逗号分隔为数组1,2,3 => ['1','2','3']const list: Array<string> = str.split(',')for (let i = 0; i < list.length; i++) {map[list[i]] = true}// expectsLowerCase为true,对参数进行小写转换,否则不变, 最后判断是不是在str中存在return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]}export const isReservedProp = /*#__PURE__*/ makeMap(// the leading comma is intentional so empty string "" is also included',key,ref,' +'onVnodeBeforeMount,onVnodeMounted,' +'onVnodeBeforeUpdate,onVnodeUpdated,' +'onVnodeBeforeUnmount,onVnodeUnmounted')// example:isReservedProp(''); // trueisReservedProp('key'); // trueisReservedProp('ref'); // trueisReservedProp('onVnodeBeforeMount'); // trueisReservedProp('onVnodeMounted'); // trueisReservedProp('onVnodeBeforeUpdate'); // trueisReservedProp('onVnodeUpdated'); // trueisReservedProp('onVnodeBeforeUnmount'); // trueisReservedProp('onVnodeUnmounted'); // true
2.14 cacheStringFunction 缓存
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {const cache: Record<string, string> = Object.create(null)return ((str: string) => {const hit = cache[str]return hit || (cache[str] = fn(str))}) as any}
2.15 一些正则函数
const camelizeRE = /-(\w)/g/*** 连字符转换驼峰* @private*/export const camelize = cacheStringFunction((str: string): string => {return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))})// example:camelize('list-item') // listItemconst hyphenateRE = /\B([A-Z])/g/*** \B 是指 非 \b 单词边界* 驼峰转换连字符* @private*/export const hyphenate = cacheStringFunction((str: string) =>str.replace(hyphenateRE, '-$1').toLowerCase())// example:camelize('listItem') // list-item/*** 首字母大写* @private*/export const capitalize = cacheStringFunction((str: string) => str.charAt(0).toUpperCase() + str.slice(1))/*** 给key加一个on并且单子首字母大写* @private*/export const toHandlerKey = cacheStringFunction((str: string) =>str ? `on${capitalize(str)}` : ``)const result = toHandlerKey('click');console.log(result, 'result'); // 'onClick'
2.16 hasChanged 判断是否有变化
// compare whether a value has changed, accounting for NaN.export const hasChanged = (value: any, oldValue: any): boolean =>!Object.is(value, oldValue)// example:// NaN 是不变的hasChanged(NaN, NaN); // falsehasChanged(1, 1); // falsehasChanged(1, 2); // truehasChanged(+0, -0); // false// Obect.is 认为 +0 和 -0 不是同一个值Object.is(+0, -0); // false// Object.is 认为 NaN 和 本身 相比 是同一个值Object.is(NaN, NaN); // true
2.17 invokeArrayFns 执行数组里的函数,参数相同
export const invokeArrayFns = (fns: Function[], arg?: any) => {for (let i = 0; i < fns.length; i++) {fns[i](arg)}}// exampleconst arr = [function(val){console.log(val + '1');},function(val){console.log(val + '2');},function(val){console.log(val + '3');},]invokeArrayFns(arr, 'i'); // i1 i2 i3
2.18 def 定义对象属性
export const def = (obj: object, key: string | symbol, value: any) => {Object.defineProperty(obj, key, {configurable: true,enumerable: false,value})}
Object.defineProperty的一些属性
value——当试图获取属性时所返回的值。
writable——该属性是否可写。
enumerable——该属性在for in循环中是否会被枚举。
configurable——该属性是否可被删除。
set()——该属性的更新操作所调用的函数。
get()——获取属性值时所调用的函数。
2.19 toNumber 转数字
export const toNumber = (val: any): any => {const n = parseFloat(val)return isNaN(n) ? val : n}toNumber('111'); // 111toNumber('a111'); // 'a111'parseFloat('a111'); // NaNisNaN(NaN); // true
es6有个方法专门判断是不是NaN值
Number.isNaN('a') // falseNumber.isNaN(NaN); // true
2.20 getGlobalThis 全局对象
let _globalThis: anyexport const getGlobalThis = (): any => {return (_globalThis ||// 下次执行就直接返回 _globalThis,不需要第二次继续判断了。这种写法值得我们学习。(_globalThis =typeof globalThis !== 'undefined'? globalThis: typeof self !== 'undefined'? self: typeof window !== 'undefined'? window: typeof global !== 'undefined'? global: {}))}// 如果都不存在,使用空对象。可能是微信小程序环境下。
3. 总结
- 写对象类型常量时可以在dev环境添加Object.freeze,防止被注入改写
- getGlobalThis用了大量三目运算符,其实可以用switch或者其他方式来代替,阅读性更强
写一些转换函数,截取字符,可以使用正则,正则很强大,需要好好学习
参考
- 尤雨溪开发的 vue-devtools 如何安装,为何打开文件的功能鲜有人知?
- 初学者也能看懂的 Vue3 源码中那些实用的基础工具函数
- Vue 3.2 发布了,那尤雨溪是怎么发布 Vue.js 的?
- vue-next/
- 正则表达式教程
- Promise
