1.潜复制(修改新对象会改变原对象)
var baz = {a:'hello', b: {c:'my', d:'friend'}} var foo = baz foo.a="better" console.log(foo.a)//better console.log(baz.a)//better
2.深复制(修改新对象不会改变原对象)
var baz = {a:'hello', b: {c:'my', d:'friend'}} var foo = {} var deepCopy= function(obj) { var newObj={}; for (var key in obj) { newObj[key] = typeof obj[key]==='object'? deepCopy(obj[key]): obj[key]; } return newObj; } foo = deepCopy(obj) foo.a="better" console.log(foo.a)//better console.log(baz.a)//hello
3.对象成环
const isObject = obj => Object.prototype.toString.call(obj) === '[object Object]' function deepClone(obj, hash = new WeakMap()) { if (!isObject(obj)) { return obj } // 查表 if (hash.has(obj)) return hash.get(obj) let isArray = Array.isArray(obj) let cloneObj = isArray ? [] : {} // 哈希表设值 hash.set(obj, cloneObj) let result = Object.keys(obj).map(key => { return { [key]: deepClone(obj[key], hash) } }) return Object.assign(cloneObj, ...result) }
验证:
var obj = {}; obj.a = obj; //成环 var o = deepClone(obj); console.log(o.a === o); // true