473,545 Members | 2,042 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy an Object?

Hi all

If I create an object with the following:

var ob1 = new objMyDefinedObj ect();

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 2201
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 objMyDefinedObj ect();

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(titl e,author,publis her,isbn,editio n) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

function authorObject(fi rstname, surname) {
this.firstname = firstname;
this.surname = surname;
this.name = firstname + ' ' + surname;
}
function _displayObjectP ropertiesAndMet hods() {
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.prot otype.display = _displayObjectP ropertiesAndMet hods;
authorObject.pr ototype.display = _displayObjectP ropertiesAndMet hods;

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

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

var author1 = new authorObject('D avid','Flanagan ')

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

var book2 = new cloneObject(boo k1);

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

var book3 = new cloneObject(boo k2);

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

alert(book1.dis play());
alert(book2.dis play());
alert(book3.dis play());

</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 objMyDefinedObj ect();

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(titl e,author,publis her,isbn,editio n) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

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

function _displayObjectP ropertiesAndMet hods() {
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.prot otype.display = _displayObjectP ropertiesAndMet hods;
authorObject.pr ototype.display = _displayObjectP ropertiesAndMet hods;

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

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

var author1 = new authorObject('D avid','Flanagan ')

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

var book2 = new cloneObject(boo k1);

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

var book3 = new cloneObject(boo k2);

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

alert(book1.dis play());
alert(book2.dis play());
alert(book3.dis play());

</script>


or:

Object.prototyp e.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 objMyDefinedObj ect();
>
>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(titl e,author,publis her,isbn,editio n) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.edition = edition;
}

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

function _displayObjectP ropertiesAndMet hods() {
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.prot otype.display = _displayObjectP ropertiesAndMet hods;
authorObject.pr ototype.display = _displayObjectP ropertiesAndMet hods;

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

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

var author1 = new authorObject('D avid','Flanagan ')

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

var book2 = new cloneObject(boo k1);

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

var book3 = new cloneObject(boo k2);

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

alert(book1.dis play());
alert(book2.dis play());
alert(book3.dis play());

</script>


or:

Object.prototy pe.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.prototyp e.clone = function() { return this.valueOf(); }

var book4 = book3.clone();

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

alert(book1.dis play());
alert(book2.dis play());
alert(book3.dis play());
alert(book4.dis play());
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.prototyp e.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(boo k);

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(oldO bject) {
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(old Object) {
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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
"Michael Winter" <M.******@bluey onder.co.invali d> 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(boo k);


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/rasterTriangleD OM.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
5723
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 kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC...
5
3267
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 assignment Student* john = michael; both john and michael share the same object. This type of an assignment is different then value-assignmnet semantics...
16
3123
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
8391
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 isn't permitted 3x
10
2534
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, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects,...
2
1617
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 written that "Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified...
13
2442
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 certain code syntax but more a 'code architecture' thing , I'll use simple example classes (which are certainly not complete or working...) just to...
0
7410
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7668
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3466
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1901
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.