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