1. 数据类型判断
6 j6 I) w/ ?# }" `- u Object.prototype.toString.call()返回的数据格式为 [object Object]类型,然后用slice截取第8位到倒一位,得到结果为 Object。
, B$ X2 D3 S+ H Nvar _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
} 运行结果测试:
/ Y4 I0 S u G4 [! PtoRawType({}) // Object
" O! Q& W4 A: A" wtoRawType([]) // Array
: N; p9 o5 I' ?/ Y. y0 r8 t9 RtoRawType(true) // Boolean ?: V1 P- S0 u1 {+ f: `
toRawType(undefined) // Undefined
$ S* [& G$ h, G8 ltoRawType(null) // Null
! V! c7 L! ]( H7 ^, V5 JtoRawType(function(){}) // Function
( f3 z/ ]- Q _7 b2. 利用闭包构造map缓存数据
) l l) U" K8 e' O vue中判断我们写的组件名是不是html内置标签的时候,如果用数组类遍历那么将要循环很多次获取结果,如果把数组转为对象,把标签名设置为对象的key,那么不用依次遍历查找,只需要查找一次就能获取结果,提高了查找效率。6 P0 k8 p5 f( Z, @4 \; S9 N
function makeMap (str, expectsLowerCase) {
// 构建闭包集合map
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
// 利用闭包,每次判断是否是内置标签只需调用isHTMLTag
var isHTMLTag = makeMap('html,body,base,head,link,meta,style,title')
console.log('res', isHTMLTag('body')) // true 3. 二维数组扁平化, l% z3 ?( Z' z% o7 U7 I/ f4 m
vue中_createElement格式化传入的children的时候用到了simpleNormalizeChildren函数,原来是为了拍平数组,使二维数组扁平化,类似lodash中的flatten方法。: z% x2 \5 t! O3 ^0 S4 c
// 先看lodash中的flatten
_.flatten([1, [2, [3, [4]], 5]])
// 得到结果为 [1, 2, [3, [4]], 5]
// vue中
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// es6中 等价于
function simpleNormalizeChildren (children) {
return [].concat(...children)
} 4. 方法拦截
) o* j6 D+ y3 E, Z+ k: M6 w vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。9 l% Y! h w7 l+ q2 V' r, ^
// 重写push等方法,然后再把原型指回原方法
var ARRAY_METHOD = [ 'push', 'pop', 'shift', 'unshift', 'reverse', 'sort', 'splice' ];
var array_methods = Object.create(Array.prototype);
ARRAY_METHOD.forEach(method => {
array_methods[method] = function () {
// 拦截方法
console.log('调用的是拦截的 ' + method + ' 方法,进行依赖收集');
return Array.prototype[method].apply(this, arguments);
}
}); 运行结果测试:
! Y2 i' R& U; m8 d6 o5 Q0 ]2 B' H+ Gvar arr = [1,2,3]7 u& ~- c2 x2 f ^! k% @% |3 ?3 v
arr.__proto__ = array_methods // 改变arr的原型4 w7 J$ k g) j) t! L) ~
arr.unshift(6) // 打印结果: 调用的是拦截的 unshift 方法,进行依赖收集
8 s( J/ B- v6 A5 l2 d! U$ N5. 继承的实现6 K( m! W3 ?" S
vue中调用Vue.extend实例化组件,Vue.extend就是VueComponent构造函数,而VueComponent利用Object.create继承Vue,所以在平常开发中Vue 和 Vue.extend区别不是很大。这边主要学习用es5原生方法实现继承的,当然了,es6中 class类直接用extends继承。
) k% @, n: n9 Q. P+ w- Y, U: d // 继承方法
function inheritPrototype(Son, Father) {
var prototype = Object.create(Father.prototype)
prototype.constructor = Son
// 把Father.prototype赋值给 Son.prototype
Son.prototype = prototype
}
function Father(name) {
this.name = name
this.arr = [1,2,3]
}
Father.prototype.getName = function() {
console.log(this.name)
}
function Son(name, age) {
Father.call(this, name)
this.age = age
}
inheritPrototype(Son, Father)
Son.prototype.getAge = function() {
console.log(this.age)
} 运行结果测试:
: j6 ]) ^0 P* Y+ f+ c3 }4 `- mvar son1 = new Son("AAA", 23). ?9 Y1 A; Y" T+ d7 R
son1.getName() //AAA
8 U' ^4 |# I1 Y5 }" A( l6 m7 Nson1.getAge() //23
! f2 R# y9 c& ~) s' x4 D0 Gson1.arr.push(4)
4 d+ I) Y. V7 o2 c! P3 nconsole.log(son1.arr) //1,2,3,44 g+ T9 u! B1 j7 B$ k$ D B+ g
4 w% l+ A" u, r1 a: V4 [var son2 = new Son("BBB", 24)
4 X0 x! l. ~' i& o# D( Dson2.getName() //BBB5 n/ i; X9 ?# J6 x
son2.getAge() //24
* f1 w, U+ R, w4 ?& X/ n" [* cconsole.log(son2.arr) //1,2,33 O4 ^1 x; I( o# T' B) t1 K% D
6. 执行一次
2 Q; W: k" f' n7 J- x8 P) b: S once 方法相对比较简单,直接利用闭包实现就好了。& P2 L. y$ k! x- i
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
} 7. 浅拷贝
; E* `# z: w- Y 简单的深拷贝我们可以用 JSON.stringify() 来实现,不过vue源码中的looseEqual 浅拷贝写的也很有意思,先类型判断再递归调用,总体也不难,学一下思路。
7 q: r y% N) hfunction looseEqual (a, b) {
if (a === b) { return true }
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
var isArrayA = Array.isArray(a);
var isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return a.length === b.length && a.every(function (e, i) {
return looseEqual(e, b[i])
})
} else if (!isArrayA && !isArrayB) {
var keysA = Object.keys(a);
var keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function (key) {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
} 5 Y1 x- [- b1 T1 W) ^# [# d& _
; B& @; U3 h" a1 Z7 V
|