ES5 深拷贝&浅拷贝
浅拷贝
遍历赋值
const student = {
name: 'anjiyu',
sex: 'female',
studyInfo: {
school: '河南大学',
level: '本科',
posi: '学士'
}
}
function deepCopy(srcObj){
const resObj = {};
if(srcObj instanceof Array){
resObj = [];
}
for(const key in srcObj){
resObj[key] = srcObj[key];
}
return resObj;
}
const newStu = deepCopy(student);
newStu.studyInfo.school = '河大';
console.log(`老同学的信息`,student);
/*
老同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/
console.log(`新同学的信息`,newStu);
/*
新同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/
Object.create()
以传入对象作为原型创建一个新对象,并返回。
const student = {
name: 'anjiyu',
sex: 'female',
studyInfo: {
school: '河南大学',
level: '本科',
posi: '学士'
}
}
const newStu = Object.create(student);
newStu.studyInfo.school = '河大';
console.log(`老同学的信息`,student);
/*
老同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/
console.log(`新同学的信息`,newStu.__proto__);
/*
新同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/
深拷贝
递归赋值
const student = {
name: 'anjiyu',
sex: 'female',
studyInfo: {
school: '河南大学',
level: '本科',
posi: '学士'
}
}
function deepCopy(srcObj){
const resObj = {};
if(srcObj instanceof Array){
resObj = [];
}
for(const key in srcObj){
const value = srcObj[key];
if(typeof value === 'object'){
resObj[key] = deepCopy(value);
}else{
resObj[key] = value;
}
}
return resObj;
}
const newStu = deepCopy(student);
newStu.studyInfo.school = '河大';
console.log(`老同学的信息`,student);
/*
老同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河南大学', level: '本科', posi: '学士' }
}
*/
console.log(`新同学的信息`,newStu);
/*
新同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/
JSON.parse JSON.stringify
这种方法比较常用
const student = {
name: 'anjiyu',
sex: 'female',
studyInfo: {
school: '河南大学',
level: '本科',
posi: '学士'
}
}
const newStu = JSON.parse(JSON.stringify(student));
newStu.studyInfo.school = '河大';
console.log(`老同学的信息`,student);
/*
老同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河南大学', level: '本科', posi: '学士' }
}
*/
console.log(`新同学的信息`,newStu.__proto__);
/*
新同学的信息 {
name: 'anjiyu',
sex: 'female',
studyInfo: { school: '河大', level: '本科', posi: '学士' }
}
*/