【源码共读】| Vue2工具函数

97 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情

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

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

开始

在线代码查看:github.com/vuejs/vue/b…

1、Object.freeze

Object.freeze()方法以一个对象为参数,冻结这个对象;它可以保留对象的可枚举性,可配置性,可写性和原型不被修改;它返回被冻结的对象,但不创建冻结副本

var emptyObject = Object.freeze({});

//搞个小例子测试一下
var obj = {name:'vv',age:'18'};
var obj1 = Object.freeze(obj);
console.log(obj1);//{name: "vv", age: "18"}
obj1.name = 'mm';
console.log(obj1);//{name: "vv", age: "18"}
Object.isFrozen(obj);//true

2、isUndef是否未定义

function isUndef (v) {
    return v === undefined || v === null
  }

3、isDef是否已经定义

function isDef (v) {
    return v !== undefined && v !== null
  }
//测试一下
isDef(111);//true
isDef();//false
isDef([]);//true
isDef(false);//true
isDef("");//true
isDef({});//true
isDef(NaN);//true

4、isTrue是否是true

function isTrue (v) {
    return v === true
  }

5、isFalse是否是false

function isFalse (v) {
    return v === false
  }

5、isPrimitive判断是否是原始值

/**
   * Check if value is primitive.
   */
  function isPrimitive (value) {
    return (
      typeof value === 'string' ||
      typeof value === 'number' ||
      // $flow-disable-line
      typeof value === 'symbol' ||
      typeof value === 'boolean'
    )
  }

6、isObject判断是对象,有时不需要严格区分数组和对象

function isObject (obj) {
    return obj !== null && typeof obj === 'object'
  }

7、toRawType转换成原始值

var _toString = Object.prototype.toString;//方法返回一个表示该对象的字符串

  function toRawType (value) {
    return _toString.call(value).slice(8, -1)
  }
  
  //例子
  toRawType('') // 'String'
  toRawType() // 'Undefined'
  toRawType([]) // 'Array'

8、isPlainObject是否是纯对象

function isPlainObject (obj) {
    return _toString.call(obj) === '[object Object]'
  }
  //例子
  isPlainObject([]) // false
  isPlainObject({}) // true

9、isRegExp是否是正则表达式

function isRegExp (v) {
    return _toString.call(v) === '[object RegExp]'
  }
  //例子
  isRegExp(/aaa/) // true
  isRegExp()//false

10、isValidArrayIndex是否可用的数组索引值

function isValidArrayIndex (val) {
    var n = parseFloat(String(val));
    return n >= 0 && Math.floor(n) === n && isFinite(val)
  }
  
该全局 `isFinite()` 函数用来判断被传入的参数值是否为一个有限数值(`finite number`)。
在必要情况下,参数会首先转为一个数值
//例子

11、isPromise是否是promise对象

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

12、toString转成字符串。数组、对象转成字符串

  function toString (val) {
    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.
   */
  function toNumber (val) {
    var n = parseFloat(val);
    return isNaN(n) ? val : n
  }

14、makeMap生成一个Map对象

 /**
   * Make a map and return a function for checking if a key
   * is in that map.
   */
  function makeMap (
    str,
    expectsLowerCase
  ) {
    var map = Object.create(null);
    var list = str.split(',');
    for (var i = 0; i < list.length; i++) {
      map[list[i]] = true;
    }
    return expectsLowerCase
      ? function (val) { return map[val.toLowerCase()]; }
      : function (val) { return map[val]; }
  }

15、isBuiltInTag是否内置tag

 /**
  * Check if a tag is a built-in tag.
  */
 var isBuiltInTag = makeMap('slot,component', true);

16、remove移除数组中的item

 /**
   * Remove an item from an array.
   */
  function remove (arr, item) {
    if (arr.length) {
      var index = arr.indexOf(item);
      if (index > -1) {
        return arr.splice(index, 1)
      }
    }
  }

17、hasOwn判断是不是属于自己的属性

var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
}

18、cached利用闭包特性,缓存数据

/**
 * Create a cached version of a pure function.
 */
function cached (fn) {
  var cache = Object.create(null);
  return (function cachedFn (str) {
    var hit = cache[str];
    return hit || (cache[str] = fn(str))
  })
}

19、camelizeRE连字符转小驼峰

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

20、capitalize首字母转大写

var capitalize = cached(function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
});

21、hyphenateRE小驼峰转连字符

/**
 * Hyphenate a camelCase string.
 */
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cached(function (str) {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
});

22、polyfillBind兼容老版本不支持的bind

/* istanbul ignore next */
function polyfillBind (fn, ctx) {
  function boundFn (a) {
    var 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, ctx) {
  return fn.bind(ctx)
}

var bind = Function.prototype.bind
  ? nativeBind
  : polyfillBind;

23、toArray转成数组

/**
 * Convert an Array-like object to a real Array.
 */
function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret
}

// 例子:
function fn(){
  var arr1 = toArray(arguments);
  console.log(arr1); // [1, 2, 3, 4, 5]
  var arr2 = toArray(arguments, 2);
  console.log(arr2); // [3, 4, 5]
}
fn(1,2,3,4,5);
/**
 * Mix properties into target object.
 */
function extend (to, _from) {
  for (var key in _from) {
    to[key] = _from[key];
  }
  return to
}

24、toObject转成对象

/**
 * Merge an Array of Objects into a single Object.
 */
function toObject (arr) {
  var res = {};
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]) {
      extend(res, arr[i]);
    }
  }
  return res
}

25、noop空函数

/* 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/).
 */
function noop (a, b, c) {}

26、no总返回false

/**
 * Always return false.
 */
var no = function (a, b, c) { return false; };

27、identity返回参数本身

/**
 * Return the same value.
 */
var identity = function (_) { return _; };

28、genStaticKeys生成静态属性

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

29、looseEqual宽松相等,对数组、日期、对象对比

var a = {};
var b = {};
a === b; // false
a == b; // false

/**
 * Check if two values are loosely equal - that is,
 * if they are plain objects, do they have the same shape?
 */
function looseEqual (a, b) {
  if (a === b) { return true }
  var isObjectA = isObject(a);
  var isObjectB = isObject(b);
  if (isObjectA && isObjectB) {
    try {
      var isArrayA = Array.isArray(a);
      var isArrayB = Array.isArray(b);
      if (isArrayA && isArrayB) {
        return a.length === b.length && a.every(function (e, i) {
          return looseEqual(e, b[i])
        })
      } else if (a instanceof Date && b instanceof Date) {
        return a.getTime() === b.getTime()
      } else if (!isArrayA && !isArrayB) {
        var keysA = Object.keys(a);
        var keysB = Object.keys(b);
        return keysA.length === keysB.length && keysA.every(function (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
  }
}

30、looseIndexOf宽松的indexof

/**
 * 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.
 */
function looseIndexOf (arr, val) {
  for (var i = 0; i < arr.length; i++) {
    if (looseEqual(arr[i], val)) { return i }
  }
  return -1
}

31、once确保函数只执行一次

/**
 * Ensure a function is called only once.
 */
function once (fn) {
  var called = false;
  return function () {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  }
}


const fn1 = once(function(){
  console.log('哎嘿,无论你怎么调用,我只执行一次');
});

fn1(); // '哎嘿,无论你怎么调用,我只执行一次'
fn1(); // 不输出
fn1(); // 不输出
fn1(); // 不输出

32、生命周期等

var SSR_ATTR = 'data-server-rendered';

var ASSET_TYPES = [
  'component',
  'directive',
  'filter'
];

[Vue 生命周期](https://cn.vuejs.org/v2/api/#%E9%80%89%E9%A1%B9-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90)

var LIFECYCLE_HOOKS = [
  'beforeCreate',
  'created',
  'beforeMount',
  'mounted',
  'beforeUpdate',
  'updated',
  'beforeDestroy',
  'destroyed',
  'activated',
  'deactivated',
  'errorCaptured',
  'serverPrefetch'
];

33、extend 合并

/**
 * Mix properties into target object.
 */
function extend (to, _from) {
  for (var key in _from) {
    to[key] = _from[key];
  }
  return to
}

// 例子:
const data = { name: 'v' };
const data2 = extend(data, { mp: 'vvv', name: 'vv' });
console.log(data); // { name: "vvv", mp: "vv" }
console.log(data2); // { name: "vvv", mp: "vv" }
console.log(data === data2); // true

34、isReservedAttribute 是否是保留的属性

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

isReservedAttribute('key') // true
isReservedAttribute('ref') // true
isReservedAttribute('slot') // true
isReservedAttribute('slot-scope') // true
isReservedAttribute('is') // true
isReservedAttribute('IS') // undefined

总结

耗时了两天,终于把这一章看完了。能测试的都在浏览器上跑了一下,试了试效果。收获很多,虽然可能在用的时候还要去扒拉一下。但至少此刻是读懂了,哈哈哈