likes
comments
collection
share

【源码阅读】vue2工具函数知多少

作者站长头像
站长
· 阅读数 24

已经写了两篇文章了,反思总结一下

  • 已经开始熟悉基本的写作流程,因为之前没有写作的习惯,所以刚开始时还是有点别扭,别扭在于开始强迫大脑思考,在输出文字前总有千头万绪却不知如何下笔,练习了两篇后,发现一个方法,有一个立意后可以想到哪就写到哪,最后调整文章的排版和顺序
  • 阅读源码其实比较有意思,就像看一本书,体会作者是怎么想的,代码写的多规范,对自己平时敲代码影响很大的,无形中会使自己慢慢的规范起来,不在只是为了完成业务,习惯养成,效率就自然慢慢提高。
  • 一个优秀的库或框架,是由很多优秀的程序员敲出来的,所以想快速提升自己,就要多多阅读这些库和框架的源码,当搞明白人家是如何构建的时候,就是开始自己动手做一做的时候了,后悔没有早一点参加进来,一起读源码,从“会用”到知道其原理,再到自己也能搞出来,不要放弃独立思考

先通读这三篇文章,得多读几遍才行

老规矩,准备源码,打开vue的仓库 vue 找到目录vue/src/shared/utils.ts 下面开始看一看这些工具函数是怎么写的,都是干啥用的


1. emptyObject

export const emptyObject = Object.freeze({})
//声明了一个空对象,这个对象不能做任何修改

2.isUndef

export function isUndef (v: any): boolean %checks {
  return v === undefined || v === null
}
// %checks 可查看Flow文档
// 判断一个值v是否为未定义,两种情况为未定义(Undef) undefined or null

3.isDef

export function isDef (v: any): boolean %checks {
  return v !== undefined && v !== null
}
// 参照上一个就明白了

3.isTrue

export function isTrue (v: any): boolean %checks {
  return v === true
}
// 感觉这个就是为了语义化,isTrue

4.isFalse

export function isFalse (v: any): boolean %checks {
  return v === false
}
// 同上

补充JS中假值一共有六个,如下

false
null
undefined
0
'' (空字符串)
NaN

5.isPrimitive

export function isPrimitive (value: any): boolean %checks {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    // $flow-disable-line
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}
// 检查是否为原始值,原始类型是这四种,string number boolean symbol

6.isObject

export function isObject (obj: mixed): boolean %checks {
  return obj !== null && typeof obj === 'object'
}
// 判断是否为对象,排除掉null,因为null也是oject类型

7.toRawType

/**
 * Get the raw type string of a value, e.g., [object Object].
 */
const _toString = Object.prototype.toString

export function toRawType (value: any): string {
  return _toString.call(value).slice(8, -1)
}
// [object Object] 这是内建的一种表示方法,再比如[object string] 
//  toRawType 中 raw 为"原始"的意思,通过借用toString()方法找出value值的原始类型

8.isPlainObject

/**
 * Strict object type check. Only returns true
 * for plain JavaScript objects.
 */
 const _toString = Object.prototype.toString
export function isPlainObject (obj: any): boolean {
  return _toString.call(obj) === '[object Object]'
}
//是否为纯对象

9.isRegExp

const _toString = Object.prototype.toString
export function isRegExp (v: any): boolean {
  return _toString.call(v) === '[object RegExp]'
}
// 是否为正则表达式,与上面几种方法原理相同

补充Object.prototype.toString: 每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。 Object.prototype.toString() - JavaScript | MDN (mozilla.org)

10.isValidArrayIndex

/**
 * Check if val is a valid array index.
 */
export function isValidArrayIndex (val: any): boolean {
  const n = parseFloat(String(val))
  return n >= 0 && Math.floor(n) === n && isFinite(val)
}
// 是否是可用的数组索引值

11.isPromise

export function isPromise (val: any): boolean {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}
//判断是否是 promise,没想到是这么判断promise的

12. toString

/**
 * Convert a value to a string that is actually rendered.
 */
 const _toString = Object.prototype.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)
}
//转换成字符串

13.toNumber

/**
 * Convert an input value to a number for persistence.
 * If the conversion fails, return original string.
 */
export function toNumber (val: string): number | string {
  const n = parseFloat(val)
  return isNaN(n) ? val : n
}
//转成数字,若失败就返回原值

14.makeMap

/**
 * Make a map and return a function for checking if a key
 * is in that map.
 */
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]
}
/**
 * Check if a tag is a built-in tag.
 */
export const isBuiltInTag = makeMap('slot,component', true)

/**
 * Check if an attribute is a reserved attribute.
 */
export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')

15.remove

/**
 * Remove an item from an array.
 */
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)
    }
  }
}
// 删除数组中一项

16. hasOwn

/**
 * Check whether an object has the property.
 */
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj: Object | Array<*>, key: string): boolean {
  return hasOwnProperty.call(obj, key)
}
//又是借用的思路,生成新的语义API

17.cached

/**
 * Create a cached version of a 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)
}

/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
// 连字符转小驼峰on-click => onClick

/**
 * Capitalize a string.
 */
export const capitalize = cached((str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1)
})
// 首字母转大写

/**
 * Hyphenate a camelCase string.
 */
const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str: string): string => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
})
//小驼峰转连字符

18.polyfillBind

/**
 * Simple bind polyfill for environments that do not support it,
 * e.g., PhantomJS 1.x. Technically, we don't need this anymore
 * since native bind is now performant enough in most browsers.
 * But removing it would mean breaking code that was able to run in
 * PhantomJS 1.x, so this must be kept for backward compatibility.
 */

/* istanbul ignore next */
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
}

function nativeBind (fn: Function, ctx: Object): Function {
  return fn.bind(ctx)
}

export const bind = Function.prototype.bind
  ? nativeBind
  : polyfillBind
  
//兼容老版本浏览器不支持原生的 `bind` 函数

19.toArray

/**
 * Convert an Array-like object to a real Array.
 */
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
}
// 转成数组

20.extend

/**
 * Mix properties into target object.
 */
export function extend (to: Object, _from: ?Object): Object {
  for (const key in _from) {
    to[key] = _from[key]
  }
  return to
}
// 合并继承,这个在别的地方看到过

21.toObject

/**
 * Merge an Array of Objects into a single Object.
 */
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
}
// 转成object 

22.noop

/**
 * 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) {}
// 空函数,具体干什么用的不知道
/**
 * Always return false.
 */
export const no = (a?: any, b?: any, c?: any) => false
// no函数永远返回 false

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

/**
 * Return the same value.
 */
export const identity = (_: any) => _
//返回参数本身

/**
 * Generate a string containing static keys from compiler modules.
 */
export function genStaticKeys (modules: Array<ModuleOptions>): string {
  return modules.reduce((keys, m) => {
    return keys.concat(m.staticKeys || [])
  }, []).join(',')
}

//这一部分没太懂

23.looseEqual

/**
 * Check if two values are loosely equal - that is,
 * if they are plain objects, do they have the same shape?
 */
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
  }
}
//宽松相等 所以该函数是对数组、日期、对象进行递归比对。如果内容完全相等则宽松相等
//这里抄的别人作业

24.looseIndexOf

/**
 * Return the first index at which a loosely equal value can be
 * found in the array (if value is a plain object, the array must
 * contain an object of the same shape), or -1 if it is not present.
 */
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
}
// 也是宽松相等

25.once

/**
 * Ensure a function is called only once.
 */
export function once (fn: Function): Function {
  let called = false
  return function () {
    if (!called) {
      called = true
      fn.apply(this, arguments)
    }
  }
}
// 这种写法很少用到,但好巧妙,有机会要多用用体会

收获与总结

  • 工具函数或类似工具函数,都要语义化,例如源码中的is to等,让使用者一看就知道这个函数是用来干啥的,这里就要有一定的英文储备了,一些程序上常用的词汇要多记一些
  • 功能单一,一个函数就只实现单一功能,这样写起来没有负担,用起来更没有负担,再配合TS,可以迅速提升生产效率
  • 源码中经常借用Object中的方法,写成容易理解的接口形式,这种值得借鉴,工作中应该还有很多这种情形需要这样转换