设计项目中可以使用如下封装或者使用第三方库的实现,比如loadsh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
function deepClone(obj) { var _toString = Object.prototype.toString;
if (!obj || typeof obj !== 'object') { return obj; }
if (obj.nodeType && 'cloneNode' in obj) { return obj.cloneNode(true); }
if (_toString.call(obj) === '[object Date]') { return new Date(obj.getTime()); }
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);
|