dr jerry
dr jerry

Reputation: 10026

cloning an object in Javascript maintaining instanceof

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?

Upvotes: 1

Views: 615

Answers (4)

Adam Rackis
Adam Rackis

Reputation: 83376

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)

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187262

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);

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179256

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();

Upvotes: 0

user1106925
user1106925

Reputation:

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);

Upvotes: 2

Related Questions