----完整版的
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);
/**
实现一个clone函数,对5种主要数据类型(Number 、String、Object、Array、Boolean)
*/
Object.prototype.clone = function(){// 只是用来深拷贝 对象数据,并没有浅拷贝
// var o=this.constructor === Array? []:{};
// for(var e in this){
// o[e]=typeof this[e]==="object"? this[e].clone():this[e];
// }
// return o;
var copy = this.constructor === Array ? [] : {}; //#1
for(var e in this){
if (typeof this[e] === "object") { //#2
copy[e] = this[e].clone();
} else if (typeof this[e] === "function") { //#3
copy[e] = this[e].bind(copy); //#5
} else { //#4
copy[e] = this[e]; // 这个地方 值类型 并不能出来
}
}
return copy;
}
var cn=num.clone();// 这个克隆出来 是个函数 并不是数字了,有问题
var cS =str3.clone();
var co=obj.clone();
var ca=arr.clone();
console.log("以下是 克隆"+num)
console.log(cn); // {clone: ƒ}
console.log(cS);// {0: "h", 1: "h", 2: "h", clone: ƒ}
console.log(co); //{a: 6, b: 7, clone: ƒ}
console.log(ca); // [1, 2, clone: ƒ]
function cloneDeep(obj){//深拷贝指的是object和array
if(typeof obj ==="object"){
var result=obj.constructor === Array ? [] : {};
for(var k in obj){
result[k] = cloneDeep(obj[k]);
}
return result;
}else{
return obj;
}
}
var objDep= cloneDeep(obj);
console.log("以下是 克隆"+num)
console.log(cloneDeep(num)); // 4
console.log(cloneDeep(str3));//hhh
console.log(cloneDeep(obj)); // {a: 6, b: 7, clone: ƒ}
console.log(cloneDeep(arr)); //[1, 2, clone: ƒ]
// 深拷贝的 对象 改变属性 不会源对象
objDep = {a:8,b:9,c:"aa"};
console.log(objDep)
console.log(obj)//{a: 6, b: 7}
function cloneDeep2(obj){
if(obj instanceof Array){
result = [];
var i = obj.length;
while(i--){
result[i]=cloneDeep(obj[i]);//递归深度复制
}
return result;
}else if(obj instanceof Object){
result = {};
for(var k in obj){
result[k] = cloneDeep(obj[k]);
}
return result;}else{
return obj;
}
}