[源码共读] vue2工具函数

80 阅读3分钟

本文参加了由公众号@若川视野 发起的每周源码共读活动点击了解详情一起参与。

本篇是源码共读第24期 | Vue2工具函数,点击了解本期详情

源码地址

emptyObject

使用object.freeze()创建一个冻结的空对象,创建后不可以对其属性进行修改,同时也不能添加新的属性,冻结对象的原型同样也不能修改。

export const emptyObject = Object.freeze({})

isUndef

判断传入的值是否为undefined or null。如果为undefined or null为true反之为false

export function isUndef (v: any): boolean %checks {
   return v === undefined || v === null
}

isDef

判断一个对象是否为不为空。 如果不为空为true反之为false。和上一个函数相反

 export function isDef (v: any): boolean %checks {
      return v !== undefined && v !== null
}

isTrue

判断一个传入的值是不是为true,

export function isTrue (v: any): boolean %checks {
  return v === true
}

isFalse

判断一个传入的值是不是为false,0,null,undefined,"" 都为false

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

isPrimitive

判断传入的参数是不是一个原始值,通过typeof可以获得参数的类型是什么

export function isPrimitive (value: any): boolean %checks {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    // $flow-disable-line
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}

isObject

判断参数obj是一个非空对象。函数参数是obj的mixed类型,mined为任意类型。首先判断函数是否为空,之后判断函数类型是否为object类型。最后返回bool值

export function isObject (obj: mixed): boolean %checks {
  return obj !== null && typeof obj === 'object'
}

toRawType

_tostring 获取obj对象的初始字符串即[object,object]

const _toString = Object.prototype.toString

export function toRawType (value: any): string {
  return _toString.call(value).slice(8, -1)
}

isPlainObject

判断参数类型是否为普通对象。如果是返回未true

export function isPlainObject (obj: any): boolean {
  return _toString.call(obj) === '[object Object]'
}

isRegExp

判断参数类型是否是正则表达式

export function isRegExp (v: any): boolean {
  return _toString.call(v) === '[object RegExp]'
}

isValidArrayIndex

判断参数是否是非负数以及是否是整数并且是否是有效数。是否为有效数组的索引。 通过全局函数isFinite 来判断参数是一个有限值。

export function isValidArrayIndex (val: any): boolean {
  const n = parseFloat(String(val))
  return n >= 0 && Math.floor(n) === n && isFinite(val)
}

isPromise

判断参数是否未有效值,并且判断参数中的属性是否存在.then和.catch 函数

export function isPromise (val: any): boolean {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}

toString

首先判断参数是否为空,不为空向下走。判断参数是否为数据或者是否是obj对象,如果是则使用json.stringify进行转化,反之直接使用String()包裹返回。

export function toString (val: any): string {
  return val == null
    ? ''
    : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
      ? JSON.stringify(val, null, 2)
      : String(val)
}

toNumber

通过传入的参数将字符串转化为number,使用isNaN判断参数是否非数字。如果不是数字则直接返回字符串,反之返回number

export function toNumber (val: string): number | string {
  const n = parseFloat(val)
  return isNaN(n) ? val : n
}

makeMap

通过传入的参数用来生成一个map对象,首先生成一个空的obj,之后通过拆分字符串来生成list,遍历list来给map对象进行赋值,list中的item为key,val为true从而给obj赋值。通过expectsLowerCase进行三元运算来生成函数进行返回,expectsLowerCase为true则小写,否则大写。返回函数的作用是判断值是否存在。

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]
}

isBuiltInTag

通过makeMap来生成key为slot和component且val为true的函数。

export const isBuiltInTag = makeMap('slot,component', true)

isReservedAttribute

和上一个函数同理


export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')

remove

把参数中的item从参数的list进行移除。首先判断list是否有效,之后通过indexof判断item是否存在list中,如果存在通过splice删除。

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)
    }
  }
}

hasOwn

检查一个对象是否具有该属性。参数obj是对象或者数组,key是字符串属性的键名。通过hasOwnProperty使用call的方法传入obj和key,之后返回hasOwnProperty的结果来确定对象和数组是否有对应的属性的布尔值。

const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj: Object | Array<*>, key: string): boolean {
  return hasOwnProperty.call(obj, key)
}

cached

创建一个缓存对象的函数。首先参数和返回值是函数类型,创建一个空的obj用作缓存的容器,返回一个匿名函数这个函数接受的参数为字符串,通过cache[str]来获取值,通过||进行逻辑运算如果hit有值则直接返回,如果没有则执行参数中的函数并将值换成在cache中的str属性上。

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 capitalize hyphenate

camelize 函数将字符串转化为小驼峰。 capitalize 函数将字符串转化首字母大写。 hyphenate 函数将字符串驼峰转换为连字符分割的字符串。


/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})

/**
 * 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()
})

bind

这段代码的作用是实现一个通用的函数绑定方法 bin,当原生的bind方法可用时使用原生方法,否则使用自定义的 polyfillBind 方法。

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

toArray

通过函数将类数组对象转换为array list。首先函数接受两个参数obj的list类型,start的number类型。首先对start进行判断,默认为0,之后计算数组的长度,使用new Array(i) 来生成一个新的数组,通过while的方式逆循环来进行赋值生成array数组。

/**
 * 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
}

extend

此函数是将两个obj参数进行合并,from往to上合并,内部使用for key的方式进行合并。


/**
 * Mix properties into target object.
 */
export function extend (to: Object, _from: ?Object): Object {
  for (const key in _from) {
    to[key] = _from[key]
  }
  return to
}

toObject

此函数是将传入的数组对象进行合并。使用for将数组中的对象进行不断的合并最终生成新的数组。

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
}

noop no identity


/**
 * 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

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

/**
 * Return the same value.
 */
export const identity = (_: any) => _

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
  }
}

looseIndexOf

判断val参数是否在arr数组中存在

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
}

once

此函数用于确保函数只调用一次。首先函数参数类型为函数类型,声明called为false,之后进行判断,如果called为false则执行,函数执行后将called为true,之后执行函数。


/**
 * 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)
    }
  }
}