Vue 源码中一些util函数

8,557 阅读2分钟

JS中很多开源库都有一个util文件夹,来存放一些常用的函数。这些套路属于那种常用但是不在ES规范中,同时又不足以单独为它发布一个npm模块。所以很多库都会单独写一个工具函数模块。

最进尝试阅读vue源码,看到很多有意思的函数,在这里分享一下。

Object.prototype.toString.call(arg) 和 String(arg) 的区别?

上述两个表达式都是尝试将一个参数转化为字符串,但是还是有区别的。

String(arg) 会尝试调用 arg.toString() 或者 arg.valueOf(), 所以如果arg或者arg的原型重写了这两个方法,Object.prototype.toString.call(arg) 和 String(arg) 的结果就不同

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,不要两边烦人的补充字符,我们可以

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

toRawType(null) // "Null"
toRawType(/sdfsd/) //"RegExp"

虽然看起来挺简单的,但是很难自发的领悟到这种写法,有木有。。

缓存函数计算结果

假如有这样的一个函数

function computed(str) {
  // 假设中间的计算非常耗时
  console.log('2000s have passed')
  return 'a result'
}

我们希望将一些运算结果缓存起来,第二次调用的时候直接读取缓存中的内容,我们可以怎么做呢?

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"

判断JS运行环境

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