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

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

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

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

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.


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.