Vue 源码中一些util函数

栏目: 编程语言 · 发布时间: 6年前

内容简介:JS中很多开源库都有一个util文件夹,来存放一些常用的函数。这些套路属于那种常用但是不在ES规范中,同时又不足以单独为它发布一个npm模块。所以很多库都会单独写一个工具函数模块。最进尝试阅读vue源码,看多很多有意思的函数,在这里分享一下。上述两个表达式都是尝试将一个参数转化为字符串,但是还是有区别的。

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]
复制代码
Vue 源码中一些util函数

上图是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())
}
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro HTML5 and CSS3 Design Patterns

Pro HTML5 and CSS3 Design Patterns

Michael Bowers / Apress / 2011-11-15 / GBP 35.50

Pro HTML5 and CSS3 Design Patterns is a reference book and a cookbook on how to style web pages using CSS3 and HTML5. It contains 350 ready--to--use patterns (CSS3 and HTML5 code snippets) that you ca......一起来看看 《Pro HTML5 and CSS3 Design Patterns》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具