Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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?

irt.org | Knowledge Base | JavaScript | Object | Q879 [ previous next ]

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?

The following makes use of the typeof operator which is supported in Netscape Navigator 3+ and Microsoft Internet Explorer 3+:

<script language="JavaScript"><!--
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 cloneObject(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new cloneObject(what[i]);
        }
        else
            this[i] = what[i];
    }
}

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';

function retrieveObject(what) {
    var output = '';
    for (i in what) {
        if (typeof what[i] == 'object') {
            output += retrieveObject(what[i]);
        }
        else
            output += i + ' = ' + what[i] + '\n';
    }
    return output;
}

alert(retrieveObject(book1))
alert(retrieveObject(book2))
//--></script>

Feedback on '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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.