Skip to content

Latest commit

 

History

History
41 lines (39 loc) · 1.26 KB

0308.md

File metadata and controls

41 lines (39 loc) · 1.26 KB

深拷贝

  • 正则,日期需要先判断,然后new出来,函数则可以用bind方法返回一个新函数。
let obj = {
     name: 'jack',
      reg: /hello/gi,
    info: {
          addr: 'China',
          phone: '1231231'
      },
      arr: [1, 2, 3],
      date: new Date(),
      func: function() {
         console.log('hello');
      }
  }
function deepClone(obj) {
   let target = Array.isArray(obj) ? [] : {};
    for(let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
                target[key] = deepClone(obj[key]);
            } else if (Object.prototype.toString.call(obj[key]) === '[object RegExp]') {
                target[key] = new RegExp(obj[key]);
            } else if (Object.prototype.toString.call(obj[key]) === '[object Date]') {
              target[key] = new Date(obj[key]);
            } else if (Object.prototype.toString.call(obj[key]) === '[object Function]') {
              // target[key] = eval(obj[key].toString());
              target[key] = obj[key].bind();
            } else {
              target[key] = obj[key];
            }
        }
    }
    return target;
}
let o = deepClone(obj)
console.log(o.func)