javascriptは深クローンdeepCloneを実現します.

738 ワード

//     deepClone       
/**
 *   
 * 1.         ,    
 * 2.   RegExp  Date   ,       
 * 3.         ,  
 * 4.         
 */
function deepClone (obj, hash = new WeakMap()) {
  if (obj instanceof RegExp) return new RegExp(obj)
  if (obj instanceof Date) return new Date(obj)
  if (obj === null || typeof obj !== 'object') {
    //               
    return obj
  }
  if (hash.has(obj)) {
    return hash.get(obj)
  }
  /**
   *   obj   ,  obj.constructor   [Function: Array]
   *   obj   ,  obj.constructor   [Fcuntion: Object]
   */
  let t = new obj.constructor()
  hash.set(obj, t)
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      t[key] = deepClone(obj[key], hash);
    }
  }
  return t
}