深拷贝与浅拷贝(代码实例)
程序员文章站
2022-06-30 17:11:30
浅拷贝
所谓的浅拷贝,实际上就是只赋值这个对象的所有内容,至于它引用的其他的对象,都不复制,来看一段代码
var car = {
name:"兰博基尼&...
浅拷贝
所谓的浅拷贝,实际上就是只赋值这个对象的所有内容,至于它引用的其他的对象,都不复制,来看一段代码
var car = { name:"兰博基尼" } var person = { name:"tim", age:12, car:car } //浅拷贝 person.copy = function(){ var temp = {} for(var key in this){ temp[key] = this[key]; } return temp; } var q = person.copy(); q.car.name = "劳斯莱斯"; //这里改了person中也改了,因为引用没有复制
深拷贝
深拷贝就是在浅拷贝的基础将引用的对象给复制
var car = { name:"兰博基尼" } var person = { name:"tim", age:12, car:car } var deepCopy = function(){ var temp = {} for(var key in this){ if(typeof this[key] === 'object'){ temp[key] = this[key].deepCopy(); }else{ temp[key] = this[key]; } } return temp; } car.deepCopy = deepCopy; person.deepCopy = deepCopy; var q = person.deepCopy(); q.car.name = "劳斯莱斯";//这里改了值,并不会影响person中的car.name
用递归实现深拷贝
var car = { name:"兰博基尼" } var person = { name:"tim", age:12, car:car } person.copy = function(){ var temp = {}; for(var key in this){ if(typeof this[key] === 'object'){ this[key].copy = this.copy(); temp[key] = this[key].copy(); }else{ temp[key] = this[key]; } } } var q = person.copy();