vue2工具函数阅读
变量类型检测
/**
* Get the raw type string of a value e.g. [object Object]
*/
function toRawType (value) {
return Object.prototype.toString.call(value).slice(8, -1)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return toRawType(obj) === 'Object'
}
function isRegExp (v) {
return toRawType(v) === 'RegExp'
}
//上面这段代码核心就是 Object.prototype.toString,通过对此函数的包装达到类型判断的目的
检测key是否存在map中
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (str, expectsLowerCase) {
//先构造map
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
//返回函数,形成闭包,可访问构造的map
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Check if a attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Check if value is primitive
*/
var isPrimitive = makeMap('string,number,symbol,boolean');
isPrimitive(typeof "aaa");
字符串格式化
/**
* 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 a hyphen-delimited string.
* eg: "comp-test" -> "compTest"
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
//这里是全局匹配,对匹配返回的对象都调用下面的替换函数
return str.replace(camelizeRE, function (_, c) {
//这里 _ 是 -(\w)匹配的值 c是(\w)匹配的值
return c ? c.toUpperCase() : '';
})
});
/**
* Capitalize a string.
* eg: "border" -> "Border"
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
* eg: "borderRadius" -> "border-radius"
*/
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cached(function (str) {
return str.replace(hyphenateRE, function(char){ return "-" + char.toLowerCase()})
});
/**
* "abc def ghe s".match(/\B(\w)/g) //["b", "c", "e", "f", "h", "e"]
* "abc def ghe s".match(/\b(\w)/g) //["a", "d", "g", "s"]
* \b 单词边界,如果字符的左右两边有空白字符则为单词边界
* \B 非单词边界, 字符左右两边没有空白字符
*/
伪数组转化为数组
伪数数组特性:
- 具有length属性
- 按索引方式储存数据
- 不具有数组的push,pop等方法
/**
* 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 toArray1(list, start){
//上面的toArray重新实现了Array.prototype.slice,while循环 i-- 比 i++要快
return Array.prototype.slice.call(list, start);
}