1

I want to clone an object in Javascript. I have:

 iPath = function () { this.heading = 0; this.path = []; };
 loop = new iPath();

I know with jQuery I can do something like:

 cloneLoop = $.extend(true, {}, loop);

but than

 assert(cloneLoop instanceof iPath, "fails because loop is not an iPath");

How can i do a deep clone fulfilling last assert statement?

dr jerry
  • 9,768
  • 24
  • 79
  • 122
  • "deep" extension means that sub-objects will be merged as well. `extend` does not clone an object, it does not preserve the prototype chain either. – zzzzBov Dec 21 '11 at 18:15

4 Answers4

2

How about this:

cloneLoop = $.extend(true, new iPath(), loop);

...though I'm not sure if you'd want to do a deep copy. I'd think this would be better:

cloneLoop = $.extend(new iPath(), loop);
1

If not supporting older browsers is an option, you should be able to use Object.create:

var cloneLoop = Object.create(loop);

Here's a demo

    function Foo() {
        this.x = 1;
        this.y = 1;
        this.blah = { f: "a", g: "b" };
    }

    var f = new Foo();
    var clone = Object.create(f);

    alert(clone instanceof Foo);
    alert(clone.blah.f);

alerts true, then a (at least on Chrome, older browsers will not support Object.create)

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • 1
    +1 Seems like setting it as the prototype object would be a good solution. For older browsers, you can use the typical `Object.create` patch. `function create( proto ) { function f(){} f.prototype = proto; return new f; }` –  Dec 21 '11 at 23:04
1

Extend simply copies properties from one object to another. So you have to start with a pristine copy of the object you want to copy into. So use new iPath() instead of {}.

var iPath = function () { this.heading = 0; this.path = []; };
loop = new iPath();

cloneLoop = $.extend(true, new iPath(), loop);

alert(cloneLoop instanceof iPath);
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

You'll need to write your own clone method:

Something along the lines of:

iPath.prototype = {
  clone: function () {
    var p;
    p = new iPath();
    $.extend(true, p, this);
    return p;
  }
}
cloneLoop = loop.clone();
zzzzBov
  • 174,988
  • 54
  • 320
  • 367