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>