_.cloneDeep(value)


119

_.cloneDeep(value)

_.cloneDeep與clone方法類似,cloneDeep會遞歸深度克隆一個對象

參數

value (*): 需要遞歸深度克隆的值

返回值

(*): 返回深度克隆好的值

例子

var objects = [{ 'a': 1 }, { 'b': 2 }];
 
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

源代碼:

baseClone方法和_.clone里的是同一個方法

import baseClone from './.internal/baseClone.js'

/** Used to compose bitmasks for cloning. */
const CLONE_DEEP_FLAG = 1
const CLONE_SYMBOLS_FLAG = 4

/**
 * This method is like `clone` except that it recursively clones `value`.
 *
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see clone
 * @example
 *
 * const objects = [{ 'a': 1 }, { 'b': 2 }]
 *
 * const deep = cloneDeep(objects)
 * console.log(deep[0] === objects[0])
 * // => false
 */
//與clone方法類似,cloneDeep會遞歸深度克隆一個對象
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG)
}

export default cloneDeep

baseClone

import Stack from './Stack.js'
import arrayEach from './arrayEach.js'
import assignValue from './assignValue.js'
import baseAssign from './baseAssign.js'
import baseAssignIn from './baseAssignIn.js'
import cloneBuffer from './cloneBuffer.js'
import copyArray from './copyArray.js'
import cloneArrayBuffer from './cloneArrayBuffer.js'
import cloneDataView from './cloneDataView.js'
import cloneRegExp from './cloneRegExp.js'
import cloneSymbol from './cloneSymbol.js'
import cloneTypedArray from './cloneTypedArray.js'
import copySymbols from './copySymbols.js'
import copySymbolsIn from './copySymbolsIn.js'
import getAllKeys from './getAllKeys.js'
import getAllKeysIn from './getAllKeysIn.js'
import getTag from './getTag.js'
import initCloneObject from './initCloneObject.js'
import isBuffer from '../isBuffer.js'
import isObject from '../isObject.js'
import keys from '../keys.js'
import keysIn from '../keysIn.js'

/** Used to compose bitmasks for cloning. */
//判斷克隆的類型,使用二進制掩碼標識了深克隆,淺克隆,展平克隆(將繼承屬性展平)
const CLONE_DEEP_FLAG = 1
const CLONE_FLAT_FLAG = 2
const CLONE_SYMBOLS_FLAG = 4

/** `Object#toString` result references. */
//對象的toStringTag
const argsTag = '[object Arguments]'
const arrayTag = '[object Array]'
const boolTag = '[object Boolean]'
const dateTag = '[object Date]'
const errorTag = '[object Error]'
const mapTag = '[object Map]'
const numberTag = '[object Number]'
const objectTag = '[object Object]'
const regexpTag = '[object RegExp]'
const setTag = '[object Set]'
const stringTag = '[object String]'
const symbolTag = '[object Symbol]'
const weakMapTag = '[object WeakMap]'

const arrayBufferTag = '[object ArrayBuffer]'
const dataViewTag = '[object DataView]'
const float32Tag = '[object Float32Array]'
const float64Tag = '[object Float64Array]'
const int8Tag = '[object Int8Array]'
const int16Tag = '[object Int16Array]'
const int32Tag = '[object Int32Array]'
const uint8Tag = '[object Uint8Array]'
const uint8ClampedTag = '[object Uint8ClampedArray]'
const uint16Tag = '[object Uint16Array]'
const uint32Tag = '[object Uint32Array]'

/** Used to identify `toStringTag` values supported by `clone`. */
//用來確定指定的toStringTag是否支持克隆
const cloneableTags = {}
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true
cloneableTags[errorTag] = cloneableTags[weakMapTag] = false

/** Used to check objects for own properties. */
//用於檢測是否是對象自身的屬性
const hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
//基於toStringTag初始化對象克隆
//注意:此方法只支持如下類型:`Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
function initCloneByTag(object, tag, isDeep) {
  const Ctor = object.constructor//object的構造函數
  switch (tag) {
    case arrayBufferTag://ArrayBuffer
      return cloneArrayBuffer(object)

    case boolTag://Boolean
    case dateTag://Date
      return new Ctor(+object)

    case dataViewTag://DataView
      return cloneDataView(object, isDeep)

    case float32Tag: case float64Tag:
    case int8Tag: case int16Tag: case int32Tag:
    case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
    //Float32Array Float64Array Int8Array Int16Array Int32Array Uint8Array Uint8ClampedArray Uint16Array Uint32Array
      return cloneTypedArray(object, isDeep)

    case mapTag://Map
      return new Ctor

    case numberTag:
    case stringTag:
    //Number String
      return new Ctor(object)

    case regexpTag://RegExp
      return cloneRegExp(object)

    case setTag://Set
      return new Ctor

    case symbolTag://Symbol
      return cloneSymbol(object)
  }
}

/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
//初始化數組的克隆,返回一個初始化的克隆結果,就是和原數組長度一樣的但是元素都為空位的數組
function initCloneArray(array) {
  const { length } = array//數組的長度
  const result = new array.constructor(length)//初始化結果數組

  // Add properties assigned by `RegExp#exec`.
  //將正則方法exec()返回的數組的index和input屬性克隆到結果數組上
  if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
    result.index = array.index
    result.input = array.input
  }
  return result
}

/**
 * The base implementation of `clone` and `cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {number} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
//clone和cloneDeep的基礎實現
function baseClone(value, bitmask, customizer, key, object, stack) {
  let result//克隆的結果
  const isDeep = bitmask & CLONE_DEEP_FLAG//是否是深度克隆
  const isFlat = bitmask & CLONE_FLAT_FLAG//是否是展開繼承屬性的克隆
  const isFull = bitmask & CLONE_SYMBOLS_FLAG//是否是淺克隆

  if (customizer) {//如果傳遞了自定義克隆方法,用自定義的克隆方法處理
    result = object ? customizer(value, key, object, stack) : customizer(value)
  }
  if (result !== undefined) {//如果自定義克隆處理后能夠result有變化,直接返回結果
    return result
  }
  if (!isObject(value)) {//判斷要克隆的值是否不是對象是簡單值,如果是簡單值直接返回
    return value
  }
  const isArr = Array.isArray(value)//判斷value是否是array
  const tag = getTag(value)//獲取value的toStringTag
  if (isArr) {//如果value是數組
    result = initCloneArray(value)
    //初始化克隆數組,返回一個初始化的克隆結果,就是和原數組長度一樣的但是元素都為空位的數組
    if (!isDeep) {//如果是淺克隆,調用copyArray處理
      return copyArray(value, result)
    }
  } else {//如果value不是數組
    const isFunc = typeof value == 'function'//判斷value是否是function類型

    if (isBuffer(value)) {//如果value是buffer對象
      return cloneBuffer(value, isDeep)//使用cloneBuffer克隆buffer對象
    }
    if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
      //如果value的類型是Object arguments 或者是函數並且沒有父級對象包裹
      result = (isFlat || isFunc) ? {} : initCloneObject(value)
      //初始化克隆結果,如果需要展開繼承屬性或者value是function,那初始化為空對象,否則調用initCloneObject處理
      if (!isDeep) {//如果不是深度克隆
        //先將普通屬性克隆,然后再克隆symbol屬性
        return isFlat
          ? copySymbolsIn(value, baseAssignIn(result, value))
          : copySymbols(value, baseAssign(result, value))
      }
    } else {
      if (isFunc || !cloneableTags[tag]) {
        //其他情況如果是有父級對象的function或者不支持克隆的類型
        return object ? value : {}//返回value或者空對象
      }
      result = initCloneByTag(value, tag, isDeep)
      //根據toStringTag來初始化克隆
    }
  }
  // Check for circular references and return its corresponding clone.
  //檢查循環引用並且返回對應的克隆
  stack || (stack = new Stack)//用來存放鍵值對的數據結構
  const stacked = stack.get(value)//獲取stack中的value對應的result
  if (stacked) {//如果stack中存在直接返回
    return stacked
  }
  stack.set(value, result)//設置value對應result到stack中

  if (tag == mapTag) {//如果是map數據類型
    value.forEach((subValue, key) => {//循環map復制到result上,遞歸調用baseClone復制其中的值
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack))
    })
    return result
  }

  if (tag == setTag) {//如果是set數據類型
    value.forEach((subValue) => {//循環set復制到result上,遞歸調用baseClone復制其中的值
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack))
    })
    return result
  }

  if (isTypedArray(value)) {//如果是typedArray直接返回結果
    return result
  }

  const keysFunc = isFull
    ? (isFlat ? getAllKeysIn : getAllKeys)
    : (isFlat ? keysIn : keys)//獲取對象key數組的方法根據是否需要展平繼承屬性使用不同的

  const props = isArr ? undefined : keysFunc(value)//獲取鍵組成的數組
  arrayEach(props || value, (subValue, key) => {//循環鍵數組,將值復制
    if (props) {
      key = subValue
      subValue = value[key]
    }
    // Recursively populate clone (susceptible to call stack limits).
    //遞歸克隆其值是復雜對象的情況,容易受到調用棧大小限制的影響
    assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack))
  })
  return result
}

export default baseClone

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM