Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create duplicate of Object 1

Status
Not open for further replies.

apatterno

Programmer
Nov 26, 2002
368
US
I have an object that I have created with "foo = new Object()". I would like to create a duplicate of this object, but it seems every way I try, the duplicate is actually just a reference to the same original object.

For example:

Code:
foo = new Object();
foo.member = 3;

bar = foo;
bar.member = 5;

trace(bar.member); // It outputs 5, of course
trace(foo.member); // It outputs 5 also ?!?!?

Of course that's a trivial case. But I need to duplicate the object so that the new object is completely separate from the original. Is it even possible?

All help is appreciated.
 
One way is to create a new object then loop through the properties of the object you want to dupliate and set the new object's properties to equal them:

Code:
//create objects
foo = new Object();
bar = new Object();
//assign values to one object
foo.prop1 = 12;
foo.prop2 = 15;
foo.prop3 = 'property';
//loop through these properties and copy them
for (var i in foo) {
	bar[i] = foo[i];
}
//amend properties
bar.prop1 = 13;
bar.prop2 = 16;
bar.prop3 = 'new property';
//trace out new properties
trace("bar="+bar.prop1+" "+bar.prop2+" "+bar.prop3);
//trace out original object
trace("foo="+foo.prop1+" "+foo.prop2+" "+foo.prop3);

Better still (if you're using ActionScript 2) instantiate the object as an instance of a class - then create a new class by inheritance from the original class, override the properties and then instantiate the new object.
 
Thanks, wangbar, that was the idea I needed.

I had to modify it a bit to handle nested objects recursively, though. For anyone else following this thread:

Code:
function ObjectCopy(source) {
  for (var i in source) {
    if (typeof(source[i]) == 'object') {
      this[i] = new ObjectCopy(source[i]);
    } else {
      this[i] = source[i];
    }
  }
}

I haven't tested it yet. But I will!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top