Vue2.X源码阅读-shared/util.js

754 阅读3分钟

争取在Vue3正式发布之前把Vue2.X源码阅读一遍

src
├── compiler        # 编译相关 
├── core            # 核心代码** 
├── platforms       # 平台相关的支持
├── server          # 服务端渲染
├── sfc             # .vue 文件解析
├── shared          # 全局共享

shared/util.js全局工具函数认识一遍,最好记下来

makeMap 和 cached 方法值得好好看看并用到实际项目中 
/* @flow */  vue2.x用的flow来做强类型校验,3.x全面切换TS
//空对象{}
export const emptyObject = Object.freeze({})

// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
//是没有初始化的变量或者不存在的对象
export function isUndef (v: any): boolean %checks {
  return v === undefined || v === null
}
//上面的取反,也就是值存在
export function isDef (v: any): boolean %checks {
  return v !== undefined && v !== null
}
//不做类型转化下为true
export function isTrue (v: any): boolean %checks {
  return v === true
}
//不做类型转化下为false
export function isFalse (v: any): boolean %checks {
  return v === false
}
/**
 * 检查是否基本数据类型(除去 undefined null object)
 */
export function isPrimitive (value: any): boolean %checks {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    // $flow-disable-line
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}
/**
 * 值存在的对象(typeof null === 'object')
 */
export function isObject (obj: mixed): boolean %checks {
  return obj !== null && typeof obj === 'object'
}
/**
 * 获得一个值的对象类型,如下面的Object,RegExp.
 */
const _toString = Object.prototype.toString

export function toRawType (value: any): string {
  return _toString.call(value).slice(8, -1)
}
/**
 * 简单对象,简单对象可以理解为,没有发生继承的对象,像下面RegExp对象就不是简单对象
 */
export function isPlainObject (obj: any): boolean {
  return _toString.call(obj) === '[object Object]'
}
//正则对象
export function isRegExp (v: any): boolean {
  return _toString.call(v) === '[object RegExp]'
}
/**
 * 检查是否有效的数字索引
 */
export function isValidArrayIndex (val: any): boolean {
  const n = parseFloat(String(val))
  return n >= 0 && Math.floor(n) === n && isFinite(val)
}
//是否是promise
export function isPromise (val: any): boolean {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}
/**
 * 重写了toString方法
 */
export function toString (val: any): string {
  return val == null
    ? ''
    : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
      ? JSON.stringify(val, null, 2)
      : String(val)
}
/**
 * 将字符串值转换成数值,转换失败就保持原来字符串值
 */
export function toNumber (val: string): number | string {
  const n = parseFloat(val)
  return isNaN(n) ? val : n
}
/**
 * 构建一个map对象,返回一个校验是否在这个map里的函数
 * 有点类似柯里化,例如下面isBuildInTag,正常要xxx('xxx',true,'x')这样传参校验,修改之后就可以,先构建map,再isBuildInTag('x')校验。因为在大量使用这个方法之后再要修改的化,第二种比第一种简单太多。
 */
export function makeMap (
  str: string,
  expectsLowerCase?: boolean
): (key: string) => true | void {
  const map = Object.create(null)
  const list: Array<string> = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}
/**
 * 检查是否内置的标签.
 */
export const isBuiltInTag = makeMap('slot,component', true)
/**
 * 检查是否内置属性
 */
export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')
/**
 * 从数组中移除一个子项
 */
export function remove (arr: Array<any>, item: any): Array<any> | void {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}
/**
 * 判断一个对象是否有这个属性
 */
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj: Object | Array<*>, key: string): boolean {
  return hasOwnProperty.call(obj, key)
}
/**
 * 创建一个可缓存版本的纯函数pure function, 纯函数就是不管外界上下文如何,相同的参数返回相同的值,这里做了个缓存,对同一个参数多次调用,只计算第一次,其余直接取缓存。因为是纯函数,所以每次调用返回值都一样,只需计算一次即可。在大量调用情况中会有不错的性能优化
 */
export function cached<F: Function> (fn: F): F {
  const cache = Object.create(null)
  return (function cachedFn (str: string) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }: any)
}
/**
 * 将短横连接转换成驼峰写法 abc-efg => abcEfg
 */
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
/**
 * 首字母大写.
 */
export const capitalize = cached((str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1)
})
/**
 * camelize的逆向,驼峰写法转换短横写法
 */
const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str: string): string => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
})

/* istanbul ignore next */
/*
* pollyfill Bind方法
*/
function polyfillBind (fn: Function, ctx: Object): Function {
  function boundFn (a) {
    const l = arguments.length
    return l
      ? l > 1
        ? fn.apply(ctx, arguments)
        : fn.call(ctx, a)
      : fn.call(ctx)
  }

  boundFn._length = fn.length
  return boundFn
}
//原生bind方法
function nativeBind (fn: Function, ctx: Object): Function {
  return fn.bind(ctx)
}
//对bind方法做个兼容
export const bind = Function.prototype.bind
  ? nativeBind
  : polyfillBind

/**
 * 将类数组对象转换成数组对象.
 */
export function toArray (list: any, start?: number): Array<any> {
  start = start || 0
  let i = list.length - start
  const ret: Array<any> = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}
/**
 * 扩展对象
 */
export function extend (to: Object, _from: ?Object): Object {
  for (const key in _from) {
    to[key] = _from[key]
  }
  return to
}
/**
 * 将对象数组换成单个对象,有点像数组的扩展运算[1,...[2,3,4],5]
 */
export function toObject (arr: Array<any>): Object {
  const res = {}
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) {
      extend(res, arr[i])
    }
  }
  return res
}
/* eslint-disable no-unused-vars */

/**
 * Perform no operation.
 * Stubbing args to make Flow happy without leaving useless transpiled code
 * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
 */
 //空函数
export function noop (a?: any, b?: any, c?: any) {}

 //总是false
export const no = (a?: any, b?: any, c?: any) => false

/* eslint-enable no-unused-vars */

/**
 * 返回参数自身
 */
export const identity = (_: any) => _
/**
 * 生成一个静态key的字符串,待了解Moduleoptions再了解
 */
export function genStaticKeys (modules: Array<ModuleOptions>): string {
  return modules.reduce((keys, m) => {
    return keys.concat(m.staticKeys || [])
  }, []).join(',')
}
/**
 * 检查2个值是否‘值相等’,对象判断时需要递归到属性也‘值相等’。这里不是全等,只是判断值相等。因为所在内存地址不一样
 */
export function looseEqual (a: any, b: any): boolean {
  if (a === b) return true
  const isObjectA = isObject(a)
  const isObjectB = isObject(b)
  if (isObjectA && isObjectB) {
    try {
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      if (isArrayA && isArrayB) {
        return a.length === b.length && a.every((e, i) => {
          return looseEqual(e, b[i])
        })
      } else if (a instanceof Date && b instanceof Date) {
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        return keysA.length === keysB.length && keysA.every(key => {
          return looseEqual(a[key], b[key])
        })
      } else {
        /* istanbul ignore next */
        return false
      }
    } catch (e) {
      /* istanbul ignore next */
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    return String(a) === String(b)
  } else {
    return false
  }
}
/**
 * 返回数组中第一个值全相等的子项的索引
 */
export function looseIndexOf (arr: Array<mixed>, val: mixed): number {
  for (let i = 0; i < arr.length; i++) {
    if (looseEqual(arr[i], val)) return i
  }
  return -1
}
/**
 * 保证一个函数只执行了一次
 */
export function once (fn: Function): Function {
  let called = false
  return function () {
    if (!called) {
      called = true
      fn.apply(this, arguments)
    }
  }
}