JS中不少开源库都有一个util文件夹,来存放一些经常使用的函数。这些套路属于那种经常使用可是不在ES规范中,同时又不足以单独为它发布一个npm模块。因此不少库都会单独写一个工具函数模块。vue
最进尝试阅读vue源码,看到不少有意思的函数,在这里分享一下。android
上述两个表达式都是尝试将一个参数转化为字符串,可是仍是有区别的。ios
String(arg) 会尝试调用 arg.toString() 或者 arg.valueOf(), 因此若是arg或者arg的原型重写了这两个方法,Object.prototype.toString.call(arg) 和 String(arg) 的结果就不一样chrome
const _toString = Object.prototype.toString
var obj = {}
obj.toString() // [object Object]
_toString.call(obj) // [object Object]
obj.toString = () => '111'
obj.toString() // 111
_toString.call(obj) // [object Object]
/hello/.toString() // /hello/
_toString.call(/hello/) // [object RegExp]
复制代码
上图是ES2018的截图,咱们能够知道Object.prototype.toString的规则,并且有一个规律,Object.prototype.toString的返回值老是 [object
+ tag
+ ]
,若是咱们只想要中间的tag,不要两边烦人的补充字符,咱们能够npm
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
toRawType(null) // "Null"
toRawType(/sdfsd/) //"RegExp"
复制代码
虽然看起来挺简单的,可是很难自发的领悟到这种写法,有木有。。缓存
假若有这样的一个函数weex
function computed(str) {
// 假设中间的计算很是耗时
console.log('2000s have passed')
return 'a result'
}
复制代码
咱们但愿将一些运算结果缓存起来,第二次调用的时候直接读取缓存中的内容,咱们能够怎么作呢?iphone
function cached(fn){
const cache = Object.create(null)
return function cachedFn (str) {
if ( !cache[str] ) {
cache[str] = fn(str)
}
return cache[str]
}
}
var cachedComputed = cached(computed)
cachedComputed('ss')
// 打印2000s have passed
cachedComputed('ss')
// 再也不打印
复制代码
hello-world
风格的转化为helloWorld
风格const camelizeRE = /-(\w)/g
const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
camelize('hello-world')
// "helloWorld"
复制代码
const inBrowser = typeof window !== 'undefined'
const inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform
const weexPlatform = inWeex && WXEnvironment.platform.toLowerCase()
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE = UA && /msie|trident/.test(UA)
const isIE9 = UA && UA.indexOf('msie 9.0') > 0
const isEdge = UA && UA.indexOf('edge/') > 0
const isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android')
const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios')
const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge
const isPhantomJS = UA && /phantomjs/.test(UA)
const isFF = UA && UA.match(/firefox\/(\d+)/)
复制代码
console.log.toString()
// "function log() { [native code] }"
function fn(){}
fn.toString()
// "function fn(){}"
// 因此
function isNative (Ctor){
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
复制代码