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. 二维数组扁平化' i2 I$ X- z! I% t0 t
vue中_createElement格式化传入的children的时候用到了simpleNormalizeChildren函数,原来是为了拍平数组,使二维数组扁平化,类似lodash中的flatten方法。( m" O i7 w. Y( E
// 先看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 C. I" T* G, V/ i) `8 X Q' ?8 {/ t. X vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。 5 Z J, J0 l. _; [
// 继承方法
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)
}
运行结果测试:; @& B+ P3 a5 H" Z5 p/ U' m
var son1 = new Son("AAA", 23)3 h" `/ H7 r' X$ l
son1.getName() //AAA 8 _2 q1 `: c( F4 wson1.getAge() //23# ~8 g; ]4 W4 L9 @4 l8 ^/ M6 x& c
son1.arr.push(4) 9 }) M: D G$ q( `console.log(son1.arr) //1,2,3,47 j+ A( v1 R' B( Q
& d' q' W6 H0 m2 f Kvar son2 = new Son("BBB", 24)* A, y+ u3 Z+ g% Q9 l
son2.getName() //BBB+ R T4 H) r- G( u& f
son2.getAge() //24 8 C, m+ }4 Y& h& @) X3 G& Gconsole.log(son2.arr) //1,2,3 5 o: }) n5 p+ F1 K6. 执行一次0 L P9 p' `4 }* c2 z5 K! Z
once 方法相对比较简单,直接利用闭包实现就好了。 " V3 u1 L) S, R4 t: B