克隆
function shallow(o) {
const obj = {}
for (const i in o) {
obj[i] = o[i]
}
return obj
}
const oldObj = {
a: 1,
b: ['aaa', 'bbbb'],
old: {
zwz: {
name:111
}
}
}
const newObj = shallow(oldObj)
console.log(newObj.old.zwz, oldObj.old.zwz)
console.log(newObj.old.zwz === oldObj.old.zwz)
newObj.old.zwz.name = '卓文智'
console.log(newObj.old.zwz, oldObj.old.zwz)
const newObjDeep1 = JSON.parse(JSON.stringify(oldObj))
console.log(newObjDeep1.old.zwz, oldObj.old.zwz)
console.log(newObjDeep1.old.zwz === oldObj.old.zwz)
newObjDeep1.old.zwz.name = '卓文智zzz'
console.log(newObjDeep1.old.zwz, oldObj.old.zwz)
function person(name) {
this.name = name
}
const cgl = new person('cgl')
function say() {
console.log('haaa')
}
const oldObj2 = {
a: say,
b: new Array(1),
c: new RegExp('ab+c', 'i'),
d: cgl
}
console.log('*************JSON.parse***********')
const newObj2 = JSON.parse(JSON.stringify(oldObj2))
console.log(newObj2.a, oldObj2.a);
console.log(newObj2.b[0], oldObj2.b[0]);
console.log(newObj2.c, oldObj2.c);
console.log(newObj2.d.constructor, oldObj2.d.constructor);
const isType = (obj, type) => {
if (typeof obj !== 'object') return false
const typeString = Object.prototype.toString.call(obj)
let flag
switch (type) {
case 'Array':
flag = typeString === '[object Array]'
break;
case 'Date':
flag = typeString === '[object Date]'
break;
case 'RegExp':
flag = typeString === '[object RegExp]'
break;
default:
flag = false
}
return flag
}
const getRegExp = re => {
var flags = ''
if (re.global) flags += 'g'
if (re.ignoreCase) flags += 'i'
if (re.multiline) flags += 'm'
return flags
}
const clone = parent => {
const parents = []
const children = []
const _clone = parent => {
if (parent === null ) return null
if (typeof parent !== 'object') return parent
let child,proto
if (isType(parent, 'Array')) {
child = []
} else if (isType(parent, 'RegExp')) {
child = new RegExp(parent.source, getRegExp(parent))
if (parent.lastIndex) child.lastIndex = parent.lastIndex
} else if (isType(parent, 'RegExp')) {
child = new Date(parent.getTime)
} else {
proto = Object.getPrototypeOf(parent)
child = Object.create(proto)
}
const index = parents.indexOf(parent)
if (index != -1) {
return children[index]
}
parents.push(parent)
children.push(child)
for (let i in parent) {
child[i] = _clone(parent[i])
}
return child
}
return _clone(parent)
}
console.log('*************clone***********')
const newClone = oldObj2
console.log(newClone.a, oldObj2.a);
console.log(newClone.b[0], oldObj2.b[0]);
console.log(newClone.c, oldObj2.c);
console.log(newClone.d.constructor, oldObj2.d.constructor);
参考链接