vue.js 源代码学习笔记 ----- 工具方法 share
/* @flow */ /**
* Convert a value to a string that is actually rendered.
{ .. } [ .. ] 2 => ''
*/
export function _toString (val: any): string {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2) //2 是控制字符串系列化后的空格为2
: String(val)
} /**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
刻意把 输入框的值转换成数字, 如失败, 则还原
如 '123abc' 会转换成 123
这里没有用parseInt 是因为parseInt对浮点型转换不准确, 如
parseInt(0.0000008,10) => 8 parseFloat(0.0000008,10) => 8e-7
而且对于字符串, parFloat只能按十进制来转换, parseInt('0200',8) => 128; parseFloat('0200',8) => 200
*/
export function toNumber (val: string): number | string {
const n =parseFloat(val)return isNaN(n) ? val : n
} /**
* Make a map and return a function for checking if a key
* is in that map.
输入标签 'div,slot,span'等, div或者slot作为一个对象的key, 返回一个函数
检查传入的key是否在map中
*/
export function makeMap (
str: string,
expectsLowerCase?: boolean //传入的key还可以不区分大小写
): (key: string) => true | void {
const map = Object.create(null) //这里没有使用 new Object 或者 = {}; 是为了创建没有 __proto__属性的 真空对象
const list: Array<string> = str.split(',') //这里用到了闭包, 把map 缓存了起来 for (let i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase
? val => map[val.toLowerCase()]
: val => map[val]
} /**
* Check if a tag is a built-in tag.
检查一个标签是否是 内置标签
*/
export const isBuiltInTag = makeMap('slot,component', true) /**
* Remove an item from an array
利用indexOf splice 移除一个值
*/
export function remove (arr: Array<any>, item: any): Array<any> | void {
if (arr.length) {
const index = arr.indexOf(item)
if (index > -1) {
return arr.splice(index, 1)
}
}
} /**
* Check whether the object has the property.
缓存原型方法, 避免每次去对象的原型找这个hasOwnProperty方法, 减少一丁点性能损耗
*/
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj: Object, key: string): boolean {
return hasOwnProperty.call(obj, key)
} /**
* Check if value is primitive
只有 字符串 数字 才是原始类型
*/
export function isPrimitive (value: any): boolean {
return typeof value === 'string' || typeof value === 'number'
} /**
* Create a cached version of a pure function.
利用闭包缓存一个函数执行特定参数的结果, 比如
执行 var cFn1 = cached( fn1 ); cFn1(2); 第二次调用 cFn1(2)的时候, 就可以利用第一次的结果,
适合会多次调用一个函数, 而且参数有可能重复的情况
由于是利用了缓存, 所以传入的函数应该是纯函数, 就是每次如果参数一样, 结果必须一样, 不能是random这样的函数
*/
export function cached<F: Function> (fn: F): F {
const cache = Object.create(null)
return (function cachedFn (str: string) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}: any)
} /**
* Camelize a hyphen-delimited string.
把 'ms-box-shadow' 这样的用-分割的连字符, 驼峰化 => msBoxShadow ; 有利于在js中设置样式
*/
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
//c 就是(\w)这个子项, 前面需要一个-; 所以 -box 会变成 -Box
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
}) /**
* Capitalize a string.
abc 变成 Abc
*/
export const capitalize = cached((str: string): string => {
return str.charAt(0).toUpperCase() + str.slice(1)
}) /**
* Hyphenate a camelCase string.
驼峰转成链接字符 abcAb => abc-ab
*/
const hyphenateRE = /([^-])([A-Z])/g
export const hyphenate = cached((str: string): string => {
return str
.replace(hyphenateRE, '$1-$2') //转两次?
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
}) /**
* Simple bind, faster than native
自定义的bind方法, 比原生快那么一点, 原理?
*/
export function bind (fn: Function, ctx: Object): Function {
function boundFn (a) {
const l: number = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length
return boundFn
} /**
* Convert an Array-like object to a real Array.
数组转换类数组, 这里没有用[].slice.call?
*/
export function toArray (list: any, start?: number): Array<any> {
start = start || 0
let i = list.length - start
const ret: Array<any> = new Array(i)
//这里没使用push while (i--) {
ret[i] = list[i + start]
}
return ret
} /**
* Mix properties into target object.
太简单的混入
*/
export function extend (to: Object, _from: ?Object): Object {
for (const key in _from) {
to[key] = _from[key]
}
return to
} /**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
简单判断一个对象
*/
export function isObject (obj: mixed): boolean {
return obj !== null && typeof obj === 'object'
} /**
* Strict object type check. Only returns true
* for plain JavaScript objects.
确保是一个完全的对象, 而不是数组 null RegExp 之类的东西
*/
const toString = Object.prototype.toString
const OBJECT_STRING = '[object Object]'
export function isPlainObject (obj: any): boolean {
return toString.call(obj) === OBJECT_STRING
} /**
* Merge an Array of Objects into a single Object.
['a','b'] => {0:'a',1:'b'}
*/
export function toObject (arr: Array<any>): Object {
const res = {}
for (let i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i])
}
}
return res
} /**
* Perform no operation. 一个空函数
*/
export function noop () {} /**
* Always return false. 减少书写?
*/
export const no = () => false /**
* Return same value 需要利用函数来返回相同值?
*/
export const identity = (_: any) => _ /**
* Generate a static keys string from compiler modules.
把modules的每个statickeys 链接起来 形成一个特定的静态key
*/
export function genStaticKeys (modules: Array<ModuleOptions>): string {
return modules.reduce((keys, m) => {
return keys.concat(m.staticKeys || [])
}, []).join(',')
} /**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
判断两个对象 的值是否 相等, 而不用考虑对象地址是否相同
var a = {}; var b = {}; looseEqual(a,b) => true, 对于 null 和 0 false是不相等的
*/
export function looseEqual (a: mixed, b: mixed): boolean {
const isObjectA = isObject(a)
const isObjectB = isObject(b)
if (isObjectA && isObjectB) {
try {
return JSON.stringify(a) === JSON.stringify(b)
} catch (e) {
// possible circular reference
return a === b
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
//比如 arr是 [{"a":1},...] looseIndexOf( arr, {"a":1} ) => 0
export function looseIndexOf (arr: Array<mixed>, val: mixed): number {
for (let i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) return i
}
return -1
} /**
* Ensure a function is called only once. 保证这个函数只调用一次 var f = once(fn1); f(); f()没执行fn1
*/
export function once (fn: Function): Function {
let called = false
return () => {
if (!called) {
called = true
fn()
}
}
}
vue.js 源代码学习笔记 ----- 工具方法 share的更多相关文章
- vue.js 源代码学习笔记 ----- 工具方法 env
/* @flow */ /* globals MutationObserver */ import { noop } from 'shared/util' // can we use __proto_ ...
- vue.js 源代码学习笔记 ----- 工具方法 option
/* @flow */ import Vue from '../instance/index' import config from '../config' import { warn } from ...
- vue.js 源代码学习笔记 ----- 工具方法 lang
/* @flow */ // Object.freeze 使得这个对象不能增加属性, 修改属性, 这样就保证了这个对象在任何时候都是空的 export const emptyObject = Obje ...
- vue.js 源代码学习笔记 ----- 工具方法 perf
import { inBrowser } from './env' export let mark export let measure if (process.env.NODE_ENV !== 'p ...
- vue.js 源代码学习笔记 ----- 工具方法 error
import config from '../config' import { warn } from './debug' import { inBrowser } from './env' // 这 ...
- vue.js 源代码学习笔记 ----- 工具方法 debug
import config from '../config' import { noop } from 'shared/util' let warn = noop let tip = noop let ...
- vue.js 源代码学习笔记 ----- 工具方法 props
/* @flow */ import { hasOwn, isObject, isPlainObject, capitalize, hyphenate } from 'shared/util' imp ...
- vue.js 源代码学习笔记 ----- html-parse.js
/** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resi ...
- vue.js 源代码学习笔记 ----- instance render
/* @flow */ import { warn, nextTick, toNumber, _toString, looseEqual, emptyObject, handleError, loos ...
随机推荐
- Python笔记 #02# Inner workings of lists
源:DataCamp datacamp 的 DAILY PRACTICE + 日常收集. List of lists Subset and conquer Slicing and dicing Li ...
- 优雅的处理你的Java异常
本文介绍 本文仅按照业务系统开发角度描述异常的一些处理看法.不涉及java的异常基础知识,可以自行查阅 <Java核心技术 卷I> 和 <java编程思想> 可以得到更多的基础 ...
- 学号20145322 《Java程序设计》第一周学习总结
学号20145322 <Java程序设计>第一周学习总结 教材学习内容总结 Java诞生于Sun公司,于1998年12月4日发布J2SE,约以两年为一周期推出重大版本更新. 2010年Or ...
- 20145328 《Java程序设计》实验三实验报告
20145328 <Java程序设计>实验三实验报告 实验名称 Java敏捷开发与XP实践 实验内容 XP基础 XP核心实践 相关工具 实验步骤 (一)敏捷开发与XP 敏捷开发是一种以人为 ...
- uboot下如何查看内存里的数据
答:使用md工具 md.b $address $count (从地址$address处显示$count个字节的数据,b=byte,8位) md.w $address $count (从地址$addre ...
- xstream中几个注解的含义和用法(转)
XStream是个很强大的工具,能将Java对象和xml之间相互转化.xstream不在意java类中成员变量是私有还是公有,也不在乎是否有默认构造函数.它调用方式也非常简单:从xml对象转化为jav ...
- [BZOJ2109]Plane 航空管制
Description 世博期间,上海的航空客运量大大超过了平时,随之而来的航空管制也频频 发生.最近,小X就因为航空管制,连续两次在机场被延误超过了两小时.对此, 小X表示很不满意. 在这次来烟台的 ...
- Windows Server 2008驱动安装全攻略
安装设备驱动程序原本是一件非常简单的事情,很多驱动程序在安装的时候我们只要不停单击“下一步”按钮,就能让驱动程序顺利地在对应计算机系统“落户”;不过,当身边的计算机系统升级为Windows Serve ...
- JDK 中的监控与故障处理工具-03 (jstat)
jstat : JVM statistics monitoring tool jstat 命令可以监控 JVM 虚拟机各种运行时状态信息, 包括 内存状态 ,垃圾回收 ,类的装载等信息. jstat ...
- Xampp mysql启动
因为最近项目要用到php,需要集成Xampp环境,但是并没有接触过php,从官网下载了Xampp后,基本上就是傻瓜式安装了, 完成安装界面如下: 点击Apache的start可以正常启动,点击MYSQ ...