I'm aware of $.extend
, which does almost what I need, but it also seems to 'unwrap' the prototype, by copying over all the methods as members of the new object. Is there any way to tell it to skip inherited members, or do I have to roll my own copy function?
Here's what I currently have, but I'm not sure if it can be improved upon:
function Foo() {
this.x = 3;
this.y = {a: 4};
}
Foo.prototype.z = 5;
Foo.prototype.clone = function() {
var res = new Foo();
for (var key in this) {
if (this.hasOwnProperty(key)) {
// assuming that all members are plain values or objects/arrays
if (this[key] instanceof Array) {
res[key] = $.extend(true, [], this[key]);
} else if (this[key] instanceof Object) {
res[key] = $.extend(true, {}, this[key]);
} else {
res[key] = this[key];
}
}
}
return res;
};
var foo = new Foo();
var bar1 = $.extend(true, {}, foo); // {x: 3, y: {a: 4}, z: 5, clone: function}
var bar2 = foo.clone(); // {x: 3, y: {a: 4}}
Update: looking at $.extend
implementation, it seems very similar to what I have, except for hasOwnProperty
check, so perhaps this is the best way to do it after all?