Feedback on: irt.org FAQ Knowledge Base Q879
Length:
Just right
Comments:
Good routine for cloning objects, but I think it contains a typo. "typeof i" should be "typeof what[i]", e.g.
function cloneObject(what)
{
for (i in what)
{
if (typeof what[i] == 'object')
this[i] = new cloneObject(what[i]);
else
this[i] = what[i];
}
}
Worth:
Worth reading
Comments:
this :
if (typeof i == 'object') {
doesn't work to copy objects recursively...
this:
if (typeof what[i] == 'object') {
should work better.
Worth:
Very worth reading
Comments:
Thanks for the code for cloning objects however when trying to copy a Form object in IE5.5 I get a "class not registered" error. Any ideas?
<html>
<head>
<script language="JavaScript">
function cloneObject(what) {
for (i in what) {
this[i] = what[i];
}
}
function copyForm() {
myform = new cloneObject(document.forms[0]);
alert(myform.elements[0].value);
}
</script>
</head>
<body>
<form>
<input type="text" value = "Hello">
<input type="button" value="Copy Form" onClick="copyForm()";>
</form>
</body>
</html>
Worth:
Worth reading
Length:
Too short
Technical:
Not technical enough
Comments:
This is OK provided the object is not part of a hierarchy with both parent and child pointers. If it is part of such a hierarchy, you get a recursive lop and the browser runs out of stack space.
So I do't think there is a general solution to this problem. At the very minimum you have to know which properties are parent pointers and avoid making them new cloneObjects. But that may also fail if you delete the try to restore a whole sub-tree of a hierarchy, because some of the saved parent pointers will now point to nothing.