// 先看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. 方法拦截 8 K: W R! S5 S9 w3 i, d vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。 , o- ~. G. S) e
// 继承方法
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)
}
运行结果测试:" f1 _, g* [' v# {! D* G/ F
var son1 = new Son("AAA", 23)$ e' R6 B. C$ m9 Z Z
son1.getName() //AAA - o; b, \8 M5 mson1.getAge() //23 & [7 z' D3 b4 kson1.arr.push(4) . L9 z- Y1 A4 p$ i& t. c
console.log(son1.arr) //1,2,3,4) v+ P# X# a" R7 T
( T( l- {# i5 R2 kvar son2 = new Son("BBB", 24); F% u$ s% ]& O8 m1 w1 ~
son2.getName() //BBB # ]0 g* O% V. K% Q# pson2.getAge() //24 F3 q+ N. c2 d, E, aconsole.log(son2.arr) //1,2,3 + N4 K& p/ F- z8 w4 x6. 执行一次( f9 u1 ~/ |: R
once 方法相对比较简单,直接利用闭包实现就好了。( `! @' l- L+ G1 T