I found this wonderful clone function for javascript (http://my.opera.com/GreyWyvern/blog/show.dml/1725165), but it breaks with jquery with the error:
Uncaught TypeError: Object function [removed] has no method ‘replace’
Here’s the function:
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this)
{
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object")
newObj[i] = this[i].clone();
else
newObj[i] = this[i]
}
return newObj;
};
What does replace have to do with anything?
When you extend
Object.prototype, you’re taking a risk. It forces allfor-inenumeration to addhasOwnPropertyto ensure theObject.prototypeextension isn’t included.jQuery doesn’t always include that check, presumably because of the performance impact. So somewhere along the line it’s coming across your
clonefunction in the wrong place.You’ll be better off not having it on
Object.prototype, but rather having it directly onObject.Then call it from the object…
Notice that the original function had the line…
This means that you could never clone a property named
clone. This is obviously not a good thing.