Vue2源码,生命周期的合并策略

function mergeHook (
  parentVal: ?Array<Function>,
  childVal: ?Function | ?Array<Function>
): ?Array<Function> {
  const res = childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
        ? childVal
        : [childVal]
    : parentVal
  return res
    ? dedupeHooks(res)
    : res
}

function dedupeHooks (hooks) {
  const res = []
  for (let i = 0; i < hooks.length; i++) {
    if (res.indexOf(hooks[i]) === -1) {
      res.push(hooks[i])
    }
  }
  return res
}
复制代码

在刷源码的时候,看到了这个函数mergeHook,特别是里面,三元运算符的层层嵌套

const res = childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
        ? childVal
        : [childVal]
    : parentVal
复制代码

下面分析一波

我一般是先分析最外层

// 判断childVal 是否存在, 如果不存在的话,直接返回parentVal
const res = childVal ? xxx : parentVal;

var xxx = parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
        ? childVal
        : [childVal];
        
// 再按照上面的思路

var xxx = parentVal ? parentVal.concat(childVal) : xxxx;


var xxxx =  Array.isArray(childVal)
        ? childVal
        : [childVal];
        
// 最终分解完成
        
        
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享