Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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?

You are here: irt.org | FAQ | JavaScript | Object | Q879 [ previous next ]

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

©2018 Martin Webb