1. 数据类型判断: X/ X1 g8 A! t+ z7 q# d2 e+ A, J& I
Object.prototype.toString.call()返回的数据格式为 [object Object]类型,然后用slice截取第8位到倒一位,得到结果为 Object。) H) {3 q. p* F
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
} 运行结果测试:1 j' q3 O, F4 e5 F% P
toRawType({}) // Object
/ U* z x+ z8 _* [/ y" s: ?toRawType([]) // Array ; V) q, A, g- U
toRawType(true) // Boolean
) h6 g5 N3 a: B) C' xtoRawType(undefined) // Undefined8 J6 T! A: j1 {1 b/ V, g8 }$ I6 F9 x# ~
toRawType(null) // Null
2 A7 ?+ {4 t5 r5 V0 `% u/ A# }toRawType(function(){}) // Function
- j% ~2 b$ m& H, @ Y2. 利用闭包构造map缓存数据
0 G8 ~- o: G# o* ?) |9 \' j vue中判断我们写的组件名是不是html内置标签的时候,如果用数组类遍历那么将要循环很多次获取结果,如果把数组转为对象,把标签名设置为对象的key,那么不用依次遍历查找,只需要查找一次就能获取结果,提高了查找效率。) ]( j5 |4 Y9 J2 a5 E4 ^
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. 二维数组扁平化
! C7 ~# p& J: `2 v% g h vue中_createElement格式化传入的children的时候用到了simpleNormalizeChildren函数,原来是为了拍平数组,使二维数组扁平化,类似lodash中的flatten方法。$ w; I1 Y, l* C# F! l+ }- b: ]
// 先看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. 方法拦截
6 J. [/ r: t. c vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。, ]; P1 R8 C& ?! |) F8 [
// 重写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);
}
}); 运行结果测试:
7 M0 t8 m4 }! B% T# `: }( cvar arr = [1,2,3]+ w. _* r% C+ h7 c
arr.__proto__ = array_methods // 改变arr的原型6 B, l$ A3 V; ~) I$ g
arr.unshift(6) // 打印结果: 调用的是拦截的 unshift 方法,进行依赖收集
2 K* V' Y; f" `8 \; ~) n7 D" K5. 继承的实现
6 u. W; q" D8 T$ `" m0 V' ]: l vue中调用Vue.extend实例化组件,Vue.extend就是VueComponent构造函数,而VueComponent利用Object.create继承Vue,所以在平常开发中Vue 和 Vue.extend区别不是很大。这边主要学习用es5原生方法实现继承的,当然了,es6中 class类直接用extends继承。/ j! w/ k* E4 D5 O* x
// 继承方法
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)
} 运行结果测试:1 j2 I1 |0 Z& v+ z# O! z# A
var son1 = new Son("AAA", 23)
{' f4 v: ?4 c; }$ L1 ~$ T6 Xson1.getName() //AAA
7 n) e: _3 S: ]6 E( nson1.getAge() //23
% B. P/ g( o1 I) Eson1.arr.push(4) ) T2 c g% Q* m7 K( G
console.log(son1.arr) //1,2,3,4' G! s6 G* \4 u4 _
/ ^9 z# I) c" H" {& d; h$ Q7 ?var son2 = new Son("BBB", 24)2 h' B+ p7 r" H6 W
son2.getName() //BBB& v. V8 U& E, r$ v! A: M( Y
son2.getAge() //24
# d& r1 q4 e: a' ~* kconsole.log(son2.arr) //1,2,3
& `9 K. @4 y5 ^4 x$ s* @6. 执行一次
8 \4 ^+ o* A' G# ?, T; B once 方法相对比较简单,直接利用闭包实现就好了。 A9 N ^- e+ i% ?- d
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
} 7. 浅拷贝
3 D0 F% V3 J) l( m 简单的深拷贝我们可以用 JSON.stringify() 来实现,不过vue源码中的looseEqual 浅拷贝写的也很有意思,先类型判断再递归调用,总体也不难,学一下思路。
( p) A% j M8 w3 E1 G Tfunction 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'
} % A2 j: ^4 _& D
4 ?0 i: B4 o9 G; x; h/ M
|