0

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?

riv
  • 6,846
  • 2
  • 34
  • 63
  • Since it seems you want to skip some stuff, not sure if will help, but have you reviewed $.clone to see if it would fit your needs? https://api.jquery.com/clone/ – Taplar May 05 '15 at 19:39
  • the .clone() method in jQuery only clones DOM elements. – lem2802 May 05 '15 at 19:44
  • 1
    may be for you is usefull the .extend()... http://api.jquery.com/jQuery.extend/ – lem2802 May 05 '15 at 19:45
  • I said I know about .extend, but it copies over properties from the prototype as if they were in the original object. I.e. if I copy a Foo object, I will get a plain object with x, y and z and no prototype. – riv May 05 '15 at 20:09

0 Answers0