js 中的 deepClone克隆函数


function deepClone(obj) {
    var _toString = Object.prototype.toString;
    // null, undefined, non-object, function
    if (!obj || typeof obj !== 'object') {
    return obj;
    }
    // DOM Node
    if (obj.nodeType && 'cloneNode' in obj) {
    return obj.cloneNode(true);
    }
    // Date
    if (_toString.call(obj) === '[object Date]') {
    return new Date(obj.getTime());
    }
    // RegExp
    if (_toString.call(obj) === '[object RegExp]') {
    var flags = [];
    if (obj.global) { flags.push('g'); }
    if (obj.multiline) { flags.push('m'); }
    if (obj.ignoreCase) { flags.push('i'); }
    return new RegExp(obj.source, flags.join(''));
    }
    var result = Array.isArray(obj) ? [] :
    obj.constructor ? new obj.constructor() : {};
    for (var key in obj ) {
    result[key] = deepClone(obj[key]);
    }
    return result;
   }
   function A() {
    this.a = a;
   }
   var a = {
    name: 'qiu',
    birth: new Date(),
    pattern: /qiu/gim,
    container: document.body,
    hobbys: ['book', new Date(), /aaa/gim, 111]
   };
   var c = new A();
   var b = deepClone(c);
   console.log(c.a === b.a);
   console.log(c, b);
   


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM