首页 > 其他 > 详细

Vue 源码中学得到的代码技巧

时间:2019-12-13 12:15:58      阅读:134      评论:0      收藏:0      [点我收藏+]

一, 当前环境的一系列判断

1.1 inBrowser: 检测当前宿主环境是否是浏览器

// 通过判断 `window` 对象是否存在即可
export const inBrowser = typeof window !== ‘undefined‘  

1.2 hasProto:检查当前环境是否可以使用对象的 __proto__ 属性

// 一个对象的 __proto__ 属性指向了其构造函数的原型
// 从一个空的对象字面量开始沿着原型链逐级检查。
export const hasProto = ‘__proto__‘ in {}

二. 字符串操作

2.1 isReserved:检测字符串是否以 $ 或者 _ 开头

// charCodeAt() 方法可返回指定位置的字符的 Unicode 编码
export function isReserved (str: string): boolean {
  const c = (str + ‘‘).charCodeAt(0)
  return c === 0x24 || c === 0x5F
}  

2.2 camelize: 连字符转驼峰

const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ‘‘)
})

2.3 capitalize:首字符大写

// 忽略cached
export const capitalize = cached((str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1)
})

2.4 hyphenate:驼峰转连字符

const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str: string): string => {
  return str.replace(hyphenateRE, ‘-$1‘).toLowerCase()
})

三. 类型判断

3.1 isPrimitive: 判断变量是否为原型类型

export function isPrimitive (value: any): boolean %checks {
  return (
    typeof value === ‘string‘ ||
    typeof value === ‘number‘ ||
    // $flow-disable-line
    typeof value === ‘symbol‘ ||
    typeof value === ‘boolean‘
  )
}

3.2 isRegExp: 判断变量是否为正则对象

// 使用 Object.prototype.toString 与 ‘[object RegExp]‘ 做全等对比。

export function isRegExp (v: any): boolean {
  return _toString.call(v) === ‘[object RegExp]‘
}

  

  

  

  

  

 

 

 

 

 

 

 

Vue 源码中学得到的代码技巧

原文:https://www.cnblogs.com/flyinsnow/p/12034106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!