持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第14天,点击查看活动详情
本文参加了由公众号@若川视野 发起的每周源码共读活动,点击了解详情一起参与。
参考
组长的文章:www.yuque.com/ruochuan12/…
川哥的文章:juejin.cn/post/702427…
打包编译后的源码:github.com/vuejs/vue/b…
先理解flow
他是js静态类型检查器,可以帮助我们检查代码
举个使用的例子:
value: any 这的any是指定参数的类型,这里就是所有类型都行啦
boolean %checks 指的就是要求返回的类型的布尔,加checks的原因 是在Flow中直接定义判断参数的函数,会报错:
export function isPrimitive (value: any): boolean %checks {
源码
is 判断
JavaScript中假值有六个。
false
null
undefined
0
'' (空字符串)
NaN
为了判断准确,Vue2 源码中封装了isDef、 isTrue、isFalse函数来准确判断。
isUndef 是否是未定义
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
function isUndef (v) {
return v === undefined || v === null
}
isDef 是否是已经定义
见名知意。
function isDef (v) {
return v !== undefined && v !== null
}
isTrue 是否是 true
见名知意。
function isTrue (v) {
return v === true
}
isFalse 是否是 false
见名知意。
function isFalse (v) {
return v === false
}
isPrimitive 判断值是否是原始值
判断是否是字符串、或者数字、或者 symbol、或者布尔值。
/**
* Check if value is primitive.
*/
function isPrimitive (value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
isObject 判断是对象
因为 typeof null 是 'object'。数组等用这个函数判断也是 true
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
isPlainObject 是否是纯对象
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
// 上文 isObject([]) 也是 true
// 这个就是判断对象是纯对象的方法。
// 例子:
isPlainObject([]) // false
isPlainObject({}) // true
isRegExp 是否是正则表达式
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
// 例子:
// 判断是不是正则表达式
isRegExp(/ruochuan/) // true
isValidArrayIndex 是否是可用的数组索引值
数组可用的索引值是 0 ('0')、1 ('1') 、2 ('2') ...
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
var n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
Number.isFinite更强大
isFinite(2e64); // true, 在更强壮的Number.isFinite(null)中将会得到false
isFinite('0'); // true, 在更强壮的Number.isFinite('0')中将会得到false
isPromise 判断是否是 promise
function isPromise (val) {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
// 例子:
isPromise(new Promise()) // true
这里用 isDef 判断其实相对 isObject 来判断 来说有点不严谨。但是够用。我记得promise标准就是要有个then函数
to 转化
ES2015
19.1.3.6Object.prototype.toString ( )
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
Let O be ToObject(this value).
Let isArray be IsArray(O).
ReturnIfAbrupt(isArray).
If isArray is true, let builtinTag be "Array".
Else, if O is an exotic String object, let builtinTag be "String".
Else, if O has an [[ParameterMap]] internal slot, let builtinTag be "Arguments".
Else, if O has a [[Call]] internal method, let builtinTag be "Function".
Else, if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
Else, if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
Else, if O has a [[NumberData]] internal slot, let builtinTag be "Number".
Else, if O has a [[DateValue]] internal slot, let builtinTag be "Date".
Else, if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
Else, let builtinTag be "Object".
Let tag be Get (O, @@toStringTag).
ReturnIfAbrupt(tag).
If Type(tag) is not String, let tag be builtinTag.
Return the String that is the result of concatenating "[object ", tag, and "]".
This function is the %ObjProto_toString% intrinsic object.
NOTEHistorically, this function was occasionally used to access the String value of the [[Class]] internal slot that was used in previous editions of this specification as a nominal type tag for various built-in objects. The above definition of toString preserves compatibility for legacy code that uses toString as a test for those specific kinds of built-in objects. It does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects. In addition, programs can use @@toStringTag in ways that will invalidate the reliability of such legacy type tests.
toRawType 转换成原始类型
Object.prototype.toString() 方法返回一个表示该对象类型的字符串。
/**
* Get the raw type string of a value, e.g., [object Object].
*/
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
// 例子:
toRawType('') // 'String'
toRawType() // 'Undefined'
toString 转字符串
转换成字符串。是数组或者对象并且对象的 toString 方法是 Object.prototype.toString,用 JSON.stringify 转换。
/**
* Convert a value to a string that is actually rendered.
*/
function toString (val) {
return val == null
? ''
: Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
? JSON.stringify(val, null, 2)
: String(val)
}
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
}
toArray 把类数组转成真正的数组
把类数组转换成数组,支持从哪个位置开始,默认从 0 开始。
/**
* 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);
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
}
关键词缓存
makeMap 生成一个 map (对象)
传入一个以逗号分隔的字符串,生成一个 map(键值对),并且返回一个函数检测 key 值在不在这个 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]; }
}
isBuiltInTag 是否是内置的 tag
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
isReservedAttribute 是否是保留的属性
/**
* Check if an attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
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))
})
}
camelize 连字符转小驼峰
连字符 - 转驼峰 on-click => onClick
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
capitalize 首字母转大写
首字母转大写
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
hyphenate 小驼峰转连字符
onClick => on-click
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cached(function (str) {
return str.replace(hyphenateRE, '-$1').toLowerCase()
});
对象
emptyObject
冻结对象。第一层无法修改。对象中也有判断是否冻结的方法。
/*!
* Vue.js v2.6.14
* (c) 2014-2021 Evan You
* Released under the MIT License.
*/
/* */
var emptyObject = Object.freeze({});
hasOwn 检测是否是自己的属性
不检测原型链上的
/**
* Check whether an object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
extend 合并
和assign一个意思
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
其他
remove 移除数组中的中一项
/**
* 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)
}
}
}
splice 其实是一个很耗性能的方法。删除数组中的一项,其他元素都要移动位置。
axios的拦截器也是数组,不过人家移除的时候是把相应位置的元素赋值null
polyfillBind bind 的垫片
又是axios里有类似的
/**
* 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, 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;
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) {}
no 一直返回 false
/**
* Always return false.
*/
var no = function (a, b, c) { return false; };
identity 返回参数本身
/**
* Return the same value.
*/
var identity = function (_) { return _; };
genStaticKeys 生成静态属性
生成的key,用来分辨模块的吗,比如keep-alive、diff的时候用的?留疑
/**
* Generate a string containing static keys from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
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) {
//都是对象,属性一样多个,a有的属性,b也有,且值一样
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
}
}
looseIndexOf 宽松的 indexOf
该函数实现的是宽松相等。原生的 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
}
once 确保函数只执行一次
利用闭包特性,存储状态
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
生命周期等
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'
];