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

Q878 How can I clone or make a copy of an object, rather than just make a copy of the objects reference?

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

Try the following:

<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 cloneObject(what) {
    for (i in what) {
        this[i] = what[i];
    }
}

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

var book2 = new cloneObject(book1);

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

function displayObject(what) {
    var output = '';
    for (i in what)
         output += i + ' = ' + what[i] + '\n';
    alert(output);
}

displayObject(book1);
displayObject(book2);
//--></script>

The cloneObject object accepts an objects reference and then returns another object with the same properties and property values.

©2018 Martin Webb