1. 数据类型判断' L' K8 L2 h! s& U/ o! Y+ o
Object.prototype.toString.call()返回的数据格式为 [object Object]类型,然后用slice截取第8位到倒一位,得到结果为 Object。7 R2 o7 ~( i2 C @
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
} 运行结果测试:$ D4 _8 v; a6 `2 n
toRawType({}) // Object 2 L7 _+ z! C J& g/ T
toRawType([]) // Array
8 B6 y6 u- {3 Q. {1 Y3 L) e" ytoRawType(true) // Boolean
/ o* q& X' v/ K' f1 OtoRawType(undefined) // Undefined
" M, C5 z( R! _toRawType(null) // Null9 V' D+ y( {3 g) O
toRawType(function(){}) // Function
+ x8 \# o W( H. z0 u8 O; ]2. 利用闭包构造map缓存数据
2 s) `" _& S/ M, T vue中判断我们写的组件名是不是html内置标签的时候,如果用数组类遍历那么将要循环很多次获取结果,如果把数组转为对象,把标签名设置为对象的key,那么不用依次遍历查找,只需要查找一次就能获取结果,提高了查找效率。
+ h( N' M' M( N) U; c% N) Tfunction 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. 二维数组扁平化; h% m4 [# M# G
vue中_createElement格式化传入的children的时候用到了simpleNormalizeChildren函数,原来是为了拍平数组,使二维数组扁平化,类似lodash中的flatten方法。; e- Z4 N+ e( 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. 方法拦截
+ K) o0 M3 T5 v7 ^ vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。
3 C: t# G& [ A! V! S// 重写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);
}
}); 运行结果测试:
+ L) h4 \+ f3 n7 y4 wvar arr = [1,2,3] l, h. w; a$ W1 u/ M
arr.__proto__ = array_methods // 改变arr的原型& w8 {9 ~! o( S( B
arr.unshift(6) // 打印结果: 调用的是拦截的 unshift 方法,进行依赖收集2 I+ e; N% p1 Z, n
5. 继承的实现
0 |5 V8 }7 _; g# P7 a6 y3 K vue中调用Vue.extend实例化组件,Vue.extend就是VueComponent构造函数,而VueComponent利用Object.create继承Vue,所以在平常开发中Vue 和 Vue.extend区别不是很大。这边主要学习用es5原生方法实现继承的,当然了,es6中 class类直接用extends继承。
: L% ?+ z2 S; {0 M; ?' b // 继承方法
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)
} 运行结果测试:7 }" ~! A2 }" @$ C
var son1 = new Son("AAA", 23)2 o9 @$ R9 Q7 M8 f; ~
son1.getName() //AAA
; n& [9 L8 F6 _0 e0 [' b3 hson1.getAge() //23- y7 \: S( Q$ C$ I9 j9 G: b
son1.arr.push(4)
y- M, s$ S U- Wconsole.log(son1.arr) //1,2,3,4" y+ q1 }; B0 j2 c
9 d+ G% A+ ^( c, ~5 \4 L
var son2 = new Son("BBB", 24)
! a' G/ X& E0 ]8 Qson2.getName() //BBB
% S! u B" |" lson2.getAge() //24: G! }( G( W( A7 a6 G
console.log(son2.arr) //1,2,3( U8 A; e9 V0 D7 E( s
6. 执行一次
$ ]0 k5 |/ I3 e+ P! z once 方法相对比较简单,直接利用闭包实现就好了。
$ \& p6 t u: s+ s0 b5 F. ~function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
} 7. 浅拷贝
0 J2 F9 x* a4 {! q 简单的深拷贝我们可以用 JSON.stringify() 来实现,不过vue源码中的looseEqual 浅拷贝写的也很有意思,先类型判断再递归调用,总体也不难,学一下思路。2 f9 U# z) i1 _
function 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'
}
4 i" f7 \2 e i9 a* Q" I$ s
2 ^4 u$ C! ~& j9 P: W |