473,320 Members | 1,949 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Copy an Object?

Hi all

If I create an object with the following:

var ob1 = new objMyDefinedObject();

then I assign it to a new variable.

var ob2 = ob1

I know that this isn't coping the object into a new variable, its just
another reference to the SAME object unlike

var a = 20;
var b= a;

Which creates a copy of the variable "a" and stores it in variable
"b".

How can I copy my above object into a new variable rather than
reference the same object ? What I want to do is create the object, do
a load of property changes, then copy the object into a new variable
and do a load more property changes.

Thanks.

Al.
Jul 23 '05 #1
7 2194
On Tue, 03 Aug 2004 09:11:50 +0100, Harag
<ha*************@softhome.com> wrote:
Hi all

If I create an object with the following:

var ob1 = new objMyDefinedObject();

then I assign it to a new variable.

var ob2 = ob1

I know that this isn't coping the object into a new variable, its just
another reference to the SAME object unlike

var a = 20;
var b= a;

Which creates a copy of the variable "a" and stores it in variable
"b".

How can I copy my above object into a new variable rather than
reference the same object ? What I want to do is create the object, do
a load of property changes, then copy the object into a new variable
and do a load more property changes.

Thanks.

Al.

NVM, I've found a solution... not sure if its the perfect way, so if
anyone has a better way then please advise.

Code pasted below for anyone interested.

Thanks.

Al

THE CODE:
--------------------

<script type="text/javascript">
// Q879 How can I clone or make a copy of an object, rather than
// just make a copy of the objects reference, even when the object
// contains other objects?
//
// Source: http://developer.irt.org/script/object.htm
// Source: http://developer.irt.org/script/879.htm
// A couple of modificates by me to add the "method" for displaying
// objects rather than a standalone function.

function bookObject(title,author,publisher,isbn,edition) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

function authorObject(firstname, surname) {
this.firstname = firstname;
this.surname = surname;
this.name = firstname + ' ' + surname;
}
function _displayObjectPropertiesAndMethods() {
var output = '';
for (i in this){
if (typeof this[i] == 'object') {
output += this[i].display();
}
if (typeof this[i] == 'string') {
output += i + ' = ' + this[i] + '\n';
}
}
return output;
}

bookObject.prototype.display = _displayObjectPropertiesAndMethods;
authorObject.prototype.display = _displayObjectPropertiesAndMethods;

function cloneObject(whatObject) {
for (i in whatObject) {
if (typeof whatObject[i] == 'object') {
this[i] = new cloneObject(whatObject[i]);
}
else
this[i] = whatObject[i];
}
}

// Example code on how to clone....

var author1 = new authorObject('David','Flanagan')

var book1 = new bookObject('JavaScript The Definitive
Guide',author1,"O'Reilly",'1-56592-234-4','2nd Edition');

var book2 = new cloneObject(book1);

book2.edition = '3rd Edition';
book2.isbn = '1-56592-392-8';

var book3 = new cloneObject(book2);

book3.edition = '4rd Edition';
book3.isbn = '0-596-00048-0';

alert(book1.display());
alert(book2.display());
alert(book3.display());

</script>

Jul 23 '05 #2
Fox


Harag wrote:

On Tue, 03 Aug 2004 09:11:50 +0100, Harag
<ha*************@softhome.com> wrote:
Hi all

If I create an object with the following:

var ob1 = new objMyDefinedObject();

then I assign it to a new variable.

var ob2 = ob1

I know that this isn't coping the object into a new variable, its just
another reference to the SAME object unlike

var a = 20;
var b= a;

Which creates a copy of the variable "a" and stores it in variable
"b".

How can I copy my above object into a new variable rather than
reference the same object ? What I want to do is create the object, do
a load of property changes, then copy the object into a new variable
and do a load more property changes.

Thanks.

Al.


NVM, I've found a solution... not sure if its the perfect way, so if
anyone has a better way then please advise.

Code pasted below for anyone interested.

Thanks.

Al

THE CODE:
--------------------

<script type="text/javascript">
// Q879 How can I clone or make a copy of an object, rather than
// just make a copy of the objects reference, even when the object
// contains other objects?
//
// Source: http://developer.irt.org/script/object.htm
// Source: http://developer.irt.org/script/879.htm
// A couple of modificates by me to add the "method" for displaying
// objects rather than a standalone function.

function bookObject(title,author,publisher,isbn,edition) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

function authorObject(firstname, surname) {
this.firstname = firstname;
this.surname = surname;
this.name = firstname + ' ' + surname;
}

function _displayObjectPropertiesAndMethods() {
var output = '';
for (i in this){
if (typeof this[i] == 'object') {
output += this[i].display();
}
if (typeof this[i] == 'string') {
output += i + ' = ' + this[i] + '\n';
}
}
return output;
}

bookObject.prototype.display = _displayObjectPropertiesAndMethods;
authorObject.prototype.display = _displayObjectPropertiesAndMethods;

function cloneObject(whatObject) {
for (i in whatObject) {
if (typeof whatObject[i] == 'object') {
this[i] = new cloneObject(whatObject[i]);
}
else
this[i] = whatObject[i];
}
}

// Example code on how to clone....

var author1 = new authorObject('David','Flanagan')

var book1 = new bookObject('JavaScript The Definitive
Guide',author1,"O'Reilly",'1-56592-234-4','2nd Edition');

var book2 = new cloneObject(book1);

book2.edition = '3rd Edition';
book2.isbn = '1-56592-392-8';

var book3 = new cloneObject(book2);

book3.edition = '4rd Edition';
book3.isbn = '0-596-00048-0';

alert(book1.display());
alert(book2.display());
alert(book3.display());

</script>


or:

Object.prototype.clone = function() { return this.valueOf(); }

//seems to work okay
Jul 23 '05 #3
On Tue, 03 Aug 2004 05:53:28 -0500, Fox <fo*@fxmahoney.com> wrote:


Harag wrote:

On Tue, 03 Aug 2004 09:11:50 +0100, Harag
<ha*************@softhome.com> wrote:
>Hi all
>
>If I create an object with the following:
>
>var ob1 = new objMyDefinedObject();
>
>then I assign it to a new variable.
>
>var ob2 = ob1
>
>I know that this isn't coping the object into a new variable, its just
>another reference to the SAME object unlike
>
>var a = 20;
>var b= a;
>
>Which creates a copy of the variable "a" and stores it in variable
>"b".
>
>How can I copy my above object into a new variable rather than
>reference the same object ? What I want to do is create the object, do
>a load of property changes, then copy the object into a new variable
>and do a load more property changes.
>
>Thanks.
>
>Al.


NVM, I've found a solution... not sure if its the perfect way, so if
anyone has a better way then please advise.

Code pasted below for anyone interested.

Thanks.

Al

THE CODE:
--------------------

<script type="text/javascript">
// Q879 How can I clone or make a copy of an object, rather than
// just make a copy of the objects reference, even when the object
// contains other objects?
//
// Source: http://developer.irt.org/script/object.htm
// Source: http://developer.irt.org/script/879.htm
// A couple of modificates by me to add the "method" for displaying
// objects rather than a standalone function.

function bookObject(title,author,publisher,isbn,edition) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

function authorObject(firstname, surname) {
this.firstname = firstname;
this.surname = surname;
this.name = firstname + ' ' + surname;
}

function _displayObjectPropertiesAndMethods() {
var output = '';
for (i in this){
if (typeof this[i] == 'object') {
output += this[i].display();
}
if (typeof this[i] == 'string') {
output += i + ' = ' + this[i] + '\n';
}
}
return output;
}

bookObject.prototype.display = _displayObjectPropertiesAndMethods;
authorObject.prototype.display = _displayObjectPropertiesAndMethods;

function cloneObject(whatObject) {
for (i in whatObject) {
if (typeof whatObject[i] == 'object') {
this[i] = new cloneObject(whatObject[i]);
}
else
this[i] = whatObject[i];
}
}

// Example code on how to clone....

var author1 = new authorObject('David','Flanagan')

var book1 = new bookObject('JavaScript The Definitive
Guide',author1,"O'Reilly",'1-56592-234-4','2nd Edition');

var book2 = new cloneObject(book1);

book2.edition = '3rd Edition';
book2.isbn = '1-56592-392-8';

var book3 = new cloneObject(book2);

book3.edition = '4rd Edition';
book3.isbn = '0-596-00048-0';

alert(book1.display());
alert(book2.display());
alert(book3.display());

</script>


or:

Object.prototype.clone = function() { return this.valueOf(); }

//seems to work okay


Hmm I put the following near the end of the above script just before
the alerts.

Object.prototype.clone = function() { return this.valueOf(); }

var book4 = book3.clone();

book4.edition = 'Object Clone';
book4.isbn = '1-234-56789-X';

alert(book1.display());
alert(book2.display());
alert(book3.display());
alert(book4.display());
But book3 now displays the same edition name & isbn as book4 so it
looks like book4 points to the "same" object as book3 not a new
totally different object.

is this how your "clone" function is ment to work?

Thanks

Al.
Jul 23 '05 #4
On Tue, 03 Aug 2004 13:49:22 +0100, Harag <ha*************@softhome.com>
wrote:
On Tue, 03 Aug 2004 05:53:28 -0500, Fox <fo*@fxmahoney.com> wrote:
Harag wrote:
[snip]
NVM, I've found a solution... not sure if its the perfect way, so if
anyone has a better way then please advise.


It probably is the best way, though you could combine it with Fox'
suggestion:

Object.prototype.clone = function() {
var o = new Object(), p;

for(p in this) {
if('object' == typeof this[p]) {
o[p] = this[p].clone();
} else {
o[p] = this[p];
}
}
return o;
}

I would think that

var newBook = book.clone();

looks better than

var newBook = new cloneObject(book);

Also, notice that you didn't declare 'i' in your constructor, so that
would have been global.

If you want to clone arrays as well, you could use this in addition to the
code above:

Array.prototype.__clone = Array.prototype.clone;
Array.prototype.clone = function() {
var i, o = this.__clone();

for(i = 0; i < length; ++i) {
o[i] = this[i];
}
}

[snip]

Just so you know: I haven't tested these.

Mike
Please remember to trim your quotations!

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #5
Harag <ha*************@softhome.com> writes:

[objects copied as reference values]
unlike

var a = 20;
var b= a;

Which creates a copy of the variable "a" and stores it in variable
"b".
Not really. Or rather, it's impossible to tell. (And it doesn't copy
the *variable*, but the *value* that variable refers to).

Objects have identity. Two object with identical properties can still
test different when compared with "==". A simple number, boolean or
string does not have identity. One "20" is no different from another
"20". And there is a good reason for that.

Simple values are immutable. If you have the number 20, there is no
way to *change* the value. You can put another in its place, but the
value itself is always the same. Objects, on the other hand, are
mutable. You can add, remove or change properties of an object. That
makes two objects distinguishable: if you add a property to one, it
won't be on the other.

Even if simple values were copied by reference, you wouldn't be able
to tell, because they are not distinguishable in any way. Most likely,
strings are passed around as references instead of copying their
contents. With an immutable value, you don't need to know :)
How can I copy my above object into a new variable rather than
reference the same object ? What I want to do is create the object, do
a load of property changes, then copy the object into a new variable
and do a load more property changes.


The simple method is to just create a new object and copy all enumerable
properties:
---
function copyObject(oldObject) {
var newObject = new Object();
for (var propName in oldObject) {
newObject[propName] = oldObject[propName];
}
return newObject;
}
---
A sometimes more efficient method would let the new object inherit
from the old:
---
function cloneObject(oldObject) {
function Dummy(){};
dummy.prototype = oldObject;
return new Dummy();
}
---
With this latter approach, later changes to oldObject will be visible
on newObject as well, unless overwritten by changes to newObject.

Example:
---
var o1 = {x:42, y:37, z:"a test"};
var o2 = cloneObject(o1);
o1.x = "Foo";
o2.y = "Bar";
o1.y = "Baz";
alert(o2.x + o2.y); // alerts FooBar
---

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
"Michael Winter" <M.******@blueyonder.co.invalid> writes:
for(p in this) {
if('object' == typeof this[p]) {
o[p] = this[p].clone();
That would make a "deep copy". A shallow copy would not need this
distinction. Which one is desired would depend on how it's going to be
used. } I would think that

var newBook = book.clone();

looks better than

var newBook = new cloneObject(book);


The only irritation is that during the "for (p in ..." loop, "p" will
at some point be "clone", so the clone function is copied for no
real reason.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #7
Michael Winter wrote:
[snip]
If you want to clone arrays as well, you could use this in addition to
the code above:

Array.prototype.__clone = Array.prototype.clone;
Array.prototype.clone = function() {
var i, o = this.__clone();

for(i = 0; i < length; ++i) {
o[i] = this[i];
}
}
Array.prototype.clone = function() {
return this.slice(0)
}
Works for me.
Mick

[snip]

Just so you know: I haven't tested these.

Mike
Please remember to trim your quotations!

Jul 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
5
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the...
16
by: bluekite2000 | last post by:
I want Matrix A(B) to create shallow copy of B but A=B to create deep copy of B. Is that bad design? Why and why not?
5
by: lion | last post by:
in .net, if you set annstance-A of a class equal to another instance-B, a pointer will add to B, but if i want to create a copy of B instead of pointer, how to operate? Note:serialization...
10
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, ...
2
by: flamexx7 | last post by:
http://www.rafb.net/paste/results/V3TZeb28.html In this code, why copy constructor is not called while returning object from no_arg() . I was trying to find answer in C++ Standard. and there it's...
13
by: Jeroen | last post by:
Hi all, I'm trying to implement a certain class but I have problems regarding the copy ctor. I'll try to explain this as good as possible and show what I tried thusfar. Because it's not about a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.