Shallow copies: duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
var obj1 = {foo: 'foo', bar: 'bar'};
var obj2 = obj1;
any changed in obj1 will also alter the content in obj2
Deep copies: duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated. constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. deep copy is implemented as a 'prototype pattern'.
this.foo;
this.setFoo = function(value){
this.foo = value;
};
this.getFoo = function(){
return this.foo;
};
//clone method a deep copy
this.customClone = function(){
var tmp = new obj();
tmp.setFoo(this.getFoo());
return tmp;
};
};
var obj1 = new obj();
obj1.setFoo('foo');
var obj2 = obj1.customClone();
any changed in obj1 won't alter the content of obj2.
No comments:
Post a Comment