一、定义
1.浅拷贝: 将原对象或原数组的引用直接赋给新对象,新数组,新对象/数组只是原对象的一个引用
2.深拷贝: 创建一个新的对象和数组,将原对象的各项属性的“值”(数组的所有元素)拷贝过来,是“值”而不是“引用”
二、浅拷贝实践
来看以下这段代码
class Point {
//构造函数
constructor(x, y) {
this.x = x;//类中变量
this.y = y;
this.person = {};
this.person.name = 'igege';
this.person.age = 12;
}
//类中函数
toString() {
return '(' + this.x + ', ' + this.y + ','+this.person.name+','+this.person.age+')';
}
//静态函数
static sayHello(name){
//修改静态变量
this.para = name;
return 'Hello, ' + name;
}
}
var point = new Point(2,3);
fu = point;
fu.x =6;
fu.person.name ='yilian';
console.log(point.toString());
运行结果如下

分析:
在构造函数中,我们已经对x、y、person.name和person.age分别赋值了 2、3、igege、12
然后把类实例赋值给了fu,再通过fu进行对x和person.name重新赋值。
因为这是对象的浅拷贝,也就是对point的引用。对fu的属性进行了修改,也就导致了point也跟着变了
三、深拷贝实践
看以下这段代码
class Point {
//构造函数
constructor(x, y) {
this.x = x;//类中变量
this.y = y;
this.person = {};
this.person.name = 'igege';
this.person.age = 12;
}
//类中函数
toString() {
return '(' + this.x + ', ' + this.y + ','+this.person.name+','+this.person.age+')';
}
//静态函数
static sayHello(name){
//修改静态变量
this.para = name;
return 'Hello, ' + name;
}
}
var point = new Point(2,3);
fu = cloneObject(point);
fu.x =6;
fu.person.name ='yilian';
console.log(point.toString());
function cloneObject(src) {
var dest = {};
for(var key in src) {
//console.log(key);
if(typeof src === "object") dest[key] = cloneObject(src[key]);
else dest[key] = src[key];
}
return dest;
}
运行结果如下

分析:
我们对fu的变量,通过cloneObject函数转换后再赋值给fu,因为在cloneObject中,我们新创建了dest对象,然后把point的每个属性,进行赋值到dest中,这样就实现了深拷贝
当我们再对fu的x和person.name进行改变时,就不会影响到原有的point的值了
网友评论